PrimaryKeyRelatedField(source =' order.market',read_only = True)给出一个AttributeError

时间:2017-12-26 06:52:06

标签: python django django-rest-framework

models.py

class ClientTransaction(model.Models):
    order = models.ForeignKey('main.Order', related_name='client_transaction', on_delete=models.PROTECT, null=True)

class Order(BaseModel):
    market = models.ForeignKey('main.Market', on_delete=models.PROTECT, related_name='order')

serializers.py

class ClientTransactionSerializer(ModelSerializer):
    market = serializers.PrimaryKeyRelatedField(source='order.market', read_only=True)

    class Meta:
        model = ClientTransaction
        fields=['market']

给出错误:AttributeError:' NoneType'对象没有属性'市场'

django == 2,djangorestframework => 3.7.1

full error image

1 个答案:

答案 0 :(得分:0)

您需要自定义序列化程序以从ForeignKey字段获取数据。在描述的情况下,您尝试获取未初始化的订单。 尝试使用SerializerMethodField来处理此错误。例如:

class ClientTransactionSerializer(ModelSerializer):
    market = serializers.SerializerMethodField()

    def get_market(self, obj):
        return obj.order.market if obj.order else None

    class Meta:
        model = ClientTransaction
        fields=['market']