我正在使用Django 2.0
和Django REST Framework
我有一个模型来存储联系人的地址,如
class ContactAddress(models.Model):
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
city = models.CharField(max_length=250)
postal = models.CharField(max_length=6)
state = models.ForeignKey(State, on_delete=models.PROTECT, blank=True)
我还有两个模型可以存储state
和country
class Country(models.Model):
name = models.CharField(max_length=100, unique=True, verbose_name='Country Name')
class State(models.Model):
country = models.ForeignKey(Country, on_delete=models.PROTECT)
name = models.CharField(max_length=100, verbose_name='State Name')
我想在创建新的state
记录时,将POST
字段与address
数据一起传递
应用/ serializers.py
class ContactAddressSerializer(serializers.ModelSerializer):
class Meta:
model = ContactAddress
depth = 2
fields = (
'id', 'city', 'postal', 'state'
)
def create(self, validated_data):
print(validated_data)
和我的POST
数据
[
{
"city": "City Name",
"postal": "110011",
"state": "Bihar"
}
]
但state
中没有validated data
个数据。打印validate_data
返回
def create(self, validated_data):
print(validated_data)
{'city': 'City Name', 'postal': '110011', 'contact': <Contact: contact_object>}
如何传递相关字段的POST数据?
答案 0 :(得分:0)
state属性具有另一个模型的外键。如果要在序列化程序类中使用state属性,则不能表现得像简单属性
首先,为状态模型编写一个序列化程序,然后在联系地址类
中使用此序列化程序类class StateSerializer(serializers.ModelSerializer):
class meta:
Fields = ('name')
class ContactAddressSerializer(serializers.ModelSerializer):
state = StateSerializer()
class Meta:
model = ContactAddress
depth = 2
fields = (
'id', 'city', 'postal', 'state'
)
def create(self, validated_data):
print(validated_data)