Django REST Framework - 在POST数据中传递相关字段

时间:2018-05-20 12:01:34

标签: django django-rest-framework

我正在使用Django 2.0Django 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)

我还有两个模型可以存储statecountry

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数据?

1 个答案:

答案 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)