MultipleObjectsReturned: get()返回了多个Driver - 它返回了3个。

问题描述 投票:-1回答:1

我有一个DRF的API,它应该是为一个Android和IOS的前端应用提供服务。该API有三种类型的用户,即:驱动程序,客户端和管理员。司机,客户端和管理员。

客户端应该创建一个预订记录,并由API自动分配一个司机。基于可用天数和时间。目前每天(周日、周一、周二、周三、周四、周五)都是工作日,工作时间从早上7:00到晚上9:00,工作时间包括过渡期是一个小时。例如,上午9:00的预约需要一个小时,因此结束时间为10:00,所有因素都包括在内。许多司机可以在同一时间有工作。如果用户尝试预订已经选好的时段,应用应该给用户反馈。

目前我的问题是要从司机表中循环浏览已经存在的司机,将他们左键加入到预订表中,然后逐一分配他们。我能够给一个司机分配一个工作。但是当我添加司机时,就变得很困难。有一些东西我没有弄好,我不知道是什么。

这是我的模型。

""" models.py """


    """ Helper function to check overlapping times """
    def check_time_overlap(self, fixed_start, fixed_end, new_start, new_end):
        time_overlap = False
        if new_start == fixed_end or new_end == fixed_start:  # edge case
            time_overlap = False
        elif (new_start >= fixed_start and new_start <= fixed_end) or \
                (new_end >= fixed_start and new_end <= fixed_end):  \
                # innner limits
            time_overlap = True
        elif new_start <= fixed_start and new_end >= fixed_end: \
                # outter limits
            time_overlap = True

        return time_overlap

    """ Function to check overlapping bookings """
    def overlapping_bookings(self):
        if self.finishing_at <= self.booking_time:
            raise ValidationError(
                'Finishing times must be after booking times'
            )

        bookings = Booking.objects.filter(
            booking_date=self.booking_date, driver_id=self.driver
        )
        if bookings.exists():
            for booking in bookings:
                """ Check whether date and time overlaps """
                if self.check_time_overlap(
                    booking.booking_time, booking.finishing_at,
                    self.booking_time, self.finishing_at
                ):
                    """ If all drivers are allocated, raise an error \
                        message. """
                    raise ValidationError(
                        'All our drivers are booked at: ' +
                        str(booking.booking_date) + ', ' + str(
                            booking.booking_time) + '-' +
                        str(booking.finishing_at))

    def save(self, *args, **kwargs):
        self.calc_booking_total()
        self.calc_finishing_at()
        self.overlapping_bookings()
        super(Booking, self).save(*args, **kwargs)

从上面的模型中,我写了一个函数来检查同一预订日期、预订时间和结束时间的重叠时间。这个灵感来自于 ALEXANDRE PINTO on &gt.Github.IO20170715django-calendarhttps:/alexpnt.github.io20170715django-calendar。

以下是序列号



# BOOKING SERIALIZER
# ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––#


class BookingSerializer(serializers.ModelSerializer):
    package = serializers.SerializerMethodField()
    vehicle_type = serializers.SerializerMethodField()
    client_name = serializers.SerializerMethodField()
    client_phone = serializers.SerializerMethodField()

    class Meta:
        model = Booking
        # fields = '__all__'
        exclude = ('driver',)
        read_only_fields = (
            'booking_total', 'booking_status',
            'booked_at', 'finishing_at', 'client'
        )

    def get_package(self, obj):
        return obj.service.package_name

    def get_vehicle_type(self, obj):
        return obj.service.vehicle_category.name

    def get_client_name(self, obj):
        return obj.client.name

    def get_client_phone(self, obj):
        return str(obj.client.phone)

    """ Function to create booking based on authenticated client and available drivers """
    def create(self, validated_data):
        validated_data['client'] = self.context['request'].user
        validated_data['driver'] = Driver.objects.get(active=True)

        bookings = Booking.objects.create(**validated_data)
        return bookings

这是我的服务器日志。

服务器日志

django serialization django-rest-framework
1个回答
0
投票

下面是我针对以下问题创造的一个解决方案。谁都可以完善它。注意:它的帮助来自于函数 overlapping_bookings() 以便在所有司机分配完毕后,停止对单一日期和时间的预订。这将会从 overlapping_bookings() 关于 save()

希望对大家有所帮助

serializers.py,该函数覆盖了 ModelViewSet create.

def create(self, validated_data):
        """ Function to create booking objects \
        and allocate drivers automatically. """

        validated_data['client'] = self.context['request'].user

        """ Variable to save all drivers (querysets) from the driver \
        table ordered by the booking date and time. --> maybe there is \
        a better way to do it. Avoid using .get()"""

        drivers = Driver.objects.filter(active=True).order_by(
            '-booking__booking_date', '-booking__booking_time').all()

        """ Check whether the drivers querysets (list) exists """
        if drivers.exists():

            """ For loop to isolate a single query set from list of \
            quersets (drivers) """
            for drv in drivers:

                """ Condition to check for inner join query between \
                driver and booking table carefully filtering them using \
                booking_date and booking_time. This code is helped by \
                the clean() function in models. Which after every active=True \
                driver is allocated a booking, raises a ValidationError. \

                It is subject to be made better. Trying to find out how it \
                will throw a HttpResponse error instead."""

                if Booking.objects.select_related('driver').filter(
                    booking_date=validated_data['booking_date'],
                    booking_time=validated_data['booking_time'],
                ).annotate(drv=F('driver__user_ptr')).exists():
                    continue
            try:
                return Booking.objects.create(driver=drv, **validated_data)
            except Booking.DoesNotExist:
                pass
© www.soinside.com 2019 - 2024. All rights reserved.