Django Serializer - Create object with relations
<p>What I'm trying to accomplish is to create and App object through the Django REST Framework. I am using a nested Version object and relate this to a already existing client.</p>

<p>This is the model that I have, so you could get a better idea:</p>

<pre><code>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)
</code></pre>

<p>As you can see Clients can have multiples Apps(1->N), and Apps can have multiple versions (1 -> N)</p>

<p>I've implemented the following serializer so I can create the App object with the necessari relations but I must be doing something wrong:  </p>

<pre><code>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
</code></pre>

<p>My idea here is to get the pk from "clients_data['client']" which i'm sending in the POST, get the client object for that PK and assign it for this new app, and after that create the required versions.</p>

<p>But after a lot of tests the client_id in the database continuous empty. How can I assign the client correctly ?</p>

<p>Finally!</p>

<p>If it helps to someone else, you need to pass the client object to the app when you create it!</p>

<pre><code>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
</code></pre>

python django django-rest-framework