Spider
Spider

Reputation: 915

How to serialize result of objects.filter django based on foreign key object

I have two models one with a foreign key to the other:

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)

I want to get bookingdemands based on certain condition, and then serializing to have something like the code below:

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

Filtering is done like this:

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

which returns a queryset, but I can't find how to serialize them to have each booking separatly as mentionned above.

Upvotes: 2

Views: 3007

Answers (2)

JPG
JPG

Reputation: 88509

Create a serializer and set depth=1 as below

from rest_framework import serializers


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

then serialize your queryset as

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

UPDATE

# 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

Upvotes: 6

a_k_v
a_k_v

Reputation: 1608

Create two serializers BookingSerializer and BookingDemandSerializer and add

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

Upvotes: 0

Related Questions