自定义字段参考: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
直接存储外键?