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, uniq
Solution 1:
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
Post a Comment for "How To Access Other Model Field From Serializer Related Field?"