gpt4 book ai didi

python - 如何根据外键对象序列化objects.filter django的结果

转载 作者:行者123 更新时间:2023-11-30 22:07:45 30 4
gpt4 key购买 nike

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

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)

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

最佳答案

创建一个序列化器并设置深度=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

关于python - 如何根据外键对象序列化objects.filter django的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52386284/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com