Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

How to access Other Model Field from Serializer related Field?


have following model

class Search(models.Model):
   trip_choice = (
        ('O', 'One way'),
        ('R', 'return')
    )
    booking_id = models.IntegerField(db_index=True, unique=True)
    trip_type = models.CharField(max_length=20, choices=trip_choice)

and Booking Model is Fk with search

class Booking(models.Model)
    flight_search = models.ForeignKey(Search, on_delete=models.CASCADE)
    flight_id = models.CharField(
        max_length=100
    )
    return_id = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

I have following rule if trip type is Return 'R' the return id cannot be sent empty in serializer.

class AddBookSerializer(BookSerializer):
    booking_id = serializers.IntegerField(source='flight_search.booking_id')
    class Meta(BookSerializer.Meta):
      fields = (
        'booking_id',
        'flight_id',
        'return_id',
    )

   def validate_booking_id(self, value):
       print(value.trip_type)

Is there any way I can access trip type based on booking id I am really stuck here.


Solution

  • You can define a SerializerMethodField like this:

    class AddBookSerializer(BookSerializer):
        booking_id = serializers.IntegerField(source='flight_search.booking_id')
        return_id = serializers.SerializerMethodField()
    
        class Meta(BookSerializer.Meta):
            fields = (
                'booking_id',
                'flight_id',
                'return_id',
            )
    
        # by default the method name for the field is `get_{field_name}`
        # as a second argument, current instance of the `self.Meta.model` is passed
        def get_return_id(self, obj):
            if obj.flight_search.trip_choice == 'R':
                # your logic here
            else:
                return obj.return_id