如何从序列化程序相关字段访问其他模型字段?

时间:2021-05-26 08:08:21

标签: python django django-rest-framework django-serializer

有以下型号

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',我有以下规则,返回 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 访问旅行类型,我真的卡在这里了。

1 个答案:

答案 0 :(得分:0)

您可以像这样定义 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