Django Serializer - 使用关系创建对象

时间:2016-09-30 08:28:12

标签: python django django-rest-framework

我想要完成的是通过Django REST框架创建和App对象。我正在使用嵌套的Version对象并将其与已存在的客户端相关联。

这是我的模型,所以你可以得到一个更好的主意:

class Client(models.Model):
    client = models.CharField(max_length=200)
    mail = models.CharField(max_length=200, null=True)


class Keyword(models.Model):
    keyword = models.CharField(max_length=200)
    client = models.ForeignKey(Client, related_name='client_keywords',on_delete=models.CASCADE)  

class App(models.Model):
    client = models.ForeignKey(Client, related_name='client_apps', on_delete=models.CASCADE)
    appname = models.CharField(max_length=200, unique=True)

class Version(models.Model):
    apps = models.ForeignKey(App, related_name='version',on_delete=models.CASCADE)
    version = models.CharField(max_length=20, null=True)

正如您所见,客户可以拥有多个应用(1-> N),而应用可以有多个版本(1 - > N)

我已经实现了以下序列化程序,因此我可以创建具有必需关系的App对象,但我必须做错了:

class AppSerializer(serializers.ModelSerializer):
    version = VersionSerializer(many=True)
    client = ClientSerializer()

    class Meta:
        model = App
        fields = ('pk','client',..., 'version')

    def create(self, validated_data):
        versions_data = validated_data.pop('version')
        clients_data = validated_data.pop('client')
        app = App.objects.create(**validated_data)
        app.client = Client.objects.get(pk=clients_data['client'])
        for version_data in versions_data:
            Version.objects.create(apps=app, **version_data)
        return app

我的想法是从“clients_data ['client']中获取pk”我在POST中发送,获取该PK的客户端对象并为此新应用程序分配它,之后创建所需的版本

但经过大量测试后,数据库中的client_id连续为空。如何正确分配客户端?

1 个答案:

答案 0 :(得分:0)

最后!

如果它对其他人有帮助,则需要在创建时将客户端对象传递给应用程序!

class AppSerializer(serializers.ModelSerializer):
    version = VersionSerializer(many=True)
    client = ClientSerializer()

    class Meta:
        model = App
        fields = ('pk','client',..., 'version')

    def create(self, validated_data):
        versions_data = validated_data.pop('version')
        clients_data = validated_data.pop('client')
        clients_info = Client.objects.get(pk=clients_data['client'])
        app = App.objects.create(client=clients_info,**validated_data)

        for version_data in versions_data:
            Version.objects.create(apps=app, **version_data)
        return app