如何从 Serializer 相关字段访问其他模型字段?

How to access Other Model Field from Serializer related Field?

有以下型号

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)

预订模式是 Fk 搜索

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
    )

如果旅行类型是 Return 'R' 我有以下规则 return id 不能在序列化程序中发送空的。

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)

有什么方法可以根据预订 ID 访问旅行类型我真的被困在这里了。

您可以这样定义 SerializerMethodField

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