如何使用两个外键字段编写嵌套DRF序列化程序

时间:2017-01-21 15:43:36

标签: django serialization django-rest-framework

假设我有Django模型如下:

class Car(models.Model):
    name = models.CharField()
    model = models.CharField()
    type = models.CharField()

class Scooter(models.Model):
    name = models.CharField()
    model = models.CharField()
    type = models.CharField()

class User(models.Model):
    name = models.CharField()
    car = models.ForeignKeyField()
    scooter = models.ForeignKeyField()

和序列化器如下:

class CarSerializer(serializer.ModelSerializer):
    class Meta:
    model = Car
    fields = (
        'name',
        'model',
        'type'

    )

class ScooterSerializer(serializer.ModelSerializer):
    class Meta:
    model = Scooter
    fields = (
        'name',
        'model',
        'type'

    )


class UservehicleCreateSerializer(serializer.ModelSerializer):
    car = serializers.PrimaryKeyRelatedField(read_only=True)
    scooter = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
    model = User
    fields = (
    'name',
    'car',
    'scooter'
    )

所以场景是这样的: 已创建car数据和scooter数据,我们假设两者都有pk=1。我想分别使用序列化程序创建User数据。 但在我的案例中努力寻找相同的实际资源。汽车和摩托车的数据已经存在,我不需要再创建它。

尝试了DRF Documentation for writing serialized nested中的内容。

和Api post request的数据如下:

{
    'name': "Nikhil",
    'car': 1,
    'scooter': 1
}

获取错误:

IntegrityError: (1048, "Column 'car_id' cannot be null")

需要帮助。 谢谢!

1 个答案:

答案 0 :(得分:4)

尝试按如下方式编写UservehicleCreateSerializer:

class UservehicleCreateSerializer(serializer.ModelSerializer):
    car = CarSerializer(read_only=True)
    scooter = ScooterSerializer(read_only=True)
    class Meta:
        model = User
        fields = (
           'name',
           'car',
           'scooter'
        )

输出将如下:

{
'name': "Nikhil",
'car': [
    'name': "Some name",
    'model': "Some model",
    'type': "Some type"
    ],
'scooter': [
    'name': "Some name",
    'model': "Some model",
    'type': "Some type"
    ]
}

我希望这就是你所需要的。干杯! :)