简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM