如何发布一对一关系外键数据

时间:2018-07-31 16:01:41

标签: django django-rest-framework

这是我要使用rest_framework保存的当前模型。

class ModelA(models.Model):
    model_b = models.OneToOneField(ModelB, on_delete=models.CASCADE)
    some_integer_field = models.IntegerField()


class ModelB(models.Model):
    data = models.TextField()

我的序列化器:

class ModelASerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelA
        fields = ('id', 'some_integer_field', 'model_b')

class ModelBSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelB
        fields = ('id', 'data')

我要完成的工作是在发布(ModelA)时:

{
    "some_integer_field": 123,
    "model_b" : "123,123,123,432,432"
}

我希望在数据库中创建ModelB时,应填充“数据”字段,然后ModelA将使用ModelB的pk创建自身。 “数据”不可为空。它必须在那里。

2 个答案:

答案 0 :(得分:2)

可以通过重写序列化程序的create()方法来实现,

class ModelASerializer(serializers.ModelSerializer):
    model_b = serializers.CharField()

    class Meta:
        model = ModelA
        fields = ('id', 'some_integer_field', 'model_b')

        def create(self, validated_data):
            data_of_model_b = validated_data.pop('model_b')
            model_b_object, created = ModelB.objects.get_or_create(data=data_of_model_b)
            return ModelA.objects.create(**validated_data, model_b=model_b_object)

还要添加 model_b = serializers.CharField() 这一行,因为默认情况下 model_b 期望 PK 为{{ 1}}

答案 1 :(得分:1)

给出以下模型

class ModelA(models.Model):
    model_b = models.OneToOneField(ModelB, on_delete=models.CASCADE)
    some_integer_field = models.IntegerField()

class ModelB(models.Model):
    data = models.TextField()

像这样覆盖并实现串行器

class ModelBSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelB
        fields = ('data')

class ModelA(serializers.ModelSerializer):
    model_b = ModelBSerializer()

    class Meta:
        model = ModelA
        fields = ('__all__')

   def create(self, validated_data):
       model_b_validated_data = validated_data.pop('modelB') // given you have model b key value provided in your http POST payload
       modelB = ModelB.create(**model_b_validated_data)
       modelA = ModelA.create(**validated_data)
       return modelA

某些部分可能会有所不同,具体取决于您要完成的工作。但实际上,您要指定嵌套的序列化程序,并为具有关系的模型重写create方法。此实现django-rest调用可写的嵌套序列化程序。请参阅提供的链接http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers