如何基于外键对象序列化object.filter Django的结果

时间:2018-09-18 12:08:56

标签: python django django-rest-framework

我有两个模型,其中一个具有外键:

class Booking(models.Model):

type_course_requested = models.ManyToManyField(TypePost, blank=True)
    .....
    #Presentation Message

    message = models.CharField(max_length=1000)

class BookingDemand(models.Model):

    booking = models.ForeignKey(Booking, on_delete=models.CASCADE, null=True, blank=True)

我想根据特定条件获取预订需求,然后序列化为类似下面的代码:

{ 'booking1': { 'key1':...
               'bookingDemands': {....}
             }, 
  'booking2': {...}
}

过滤是这样完成的:

bookings=BookingDemand.objects.filter(booking__post__person=self.request.user)

返回一个查询集,但是如上所述,我找不到如何序列化它们以分别进行每个预订的操作。

2 个答案:

答案 0 :(得分:1)

创建一个序列化器,并如下设置 depth=1

from rest_framework import serializers


class BookingDemandSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookingDemand
        fields = '__all__'
        depth = 1

然后将查询集序列化为

bookings = BookingDemand.objects.filter(booking__post__person=self.request.user)
booking_serializer = BookingDemandSerializer(bookings, many=True)
booking_serializer.data  # here is the serialized data

更新

# serializer.py
from rest_framework import serializers


class BookingDemandSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookingDemand
        fields = '__all__'


class BookingSerializer(serializers.ModelSerializer):
    booking_demands = BookingDemandSerializer(source='bookingdemand_set', many=True)

    class Meta:
        model = Booking
        fields = '__all__'


# serialization process
queryset = Booking.objects.all()  # apply filter if you want
serializer = BookingSerializer(queryset, many=True)
serializer.data # here is the data

答案 1 :(得分:0)

创建两个序列化器 BookingSerializer和BookingDemandSerializer 并添加

booking(related_name) = BookingDemandSerializer(many=True) in BookingSerializer