在Django Rest Framework中,如何将外键值保存在to_internal_value中?

时间:2018-02-28 08:13:30

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

自定义字段参考:http://www.django-rest-framework.org/api-guide/fields/#using-source

这是我的Serializer:

class OrderSerializer(serializers.ModelSerializer):
    short_address = AddressField(source='*')
    class Meta:
        model = Order
        fields = ('id', 'order_name', 'short_address',)

自定义地址字段:

class AddressField(serializers.Field):

def to_representation(self, obj):
    ret = {
        "name": obj.address.name,
        "city": obj.address.city
    }
    return ret

def to_internal_value(self, data):
    ret = {
        "address__name": data["name"], // Not Working
        "address__city": data["city"], // Not Working
    }
    return ret

我的模型如下

class Order(models.Model):
    order_name = models.CharField(max_length=20,)
    address= models.ForeignKey(Address, null=True, on_delete=models.SET_NULL)

class Address(models.Model):
    name = models.CharField(max_length=20,)
    city = models.CharField(max_length=20,)
    state = models.CharField(max_length=20,)
    country = models.CharField(max_length=20,)

有没有办法通过to_internal_value直接存储外键?

0 个答案:

没有答案