Django-Rest-Framework. Updating nested object : <p>I'm having a problem of updating a nested object.</p>

<p>So I have a model which structure is similar to this one:</p>

<pre><code>class Invoice(models.Model):
    nr = models.CharField(max_length=100)
    title = models.CharField(max_length=100)

class InvoiceItem(models.Model):
    name = models.CharField(max_length=100)
    price = models.FloatField()
    invoice = models.ForeignKey(Invoice, related_name='items')
</code></pre>

<p>I need to create child objects from parent, and what I mean by that, is to create <code>InvoiceItems</code> directly when creating an <code>Invoice</code> object.
For this purpose, I've wrote the following serializers:</p>

<pre><code>class InvoiceItemSerializer(serializers.ModelSerializer):
    invoice = serializers.PrimaryKeyRelatedField(queryset=Invoice.objects.all(), required=False)
    class Meta:
        model = InvoiceItem


class InvoiceSerializer(serializers.ModelSerializer):
    items = InvoiceItemSerializer(many=True)

    class Meta:
        model = Invoice

    def create(self, validated_data):
        items = validated_data.pop('items', None)
        invoice = Invoice(**validated_data)
        invoice.save()
        for item in items:
            InvoiceItem.objects.create(invoice=invoice, **item)
        return invoice
</code></pre>

<p>Up till now, the create/read/delete methods work perfectly, except the <code>update</code>.
I think the below logic should be correct, but it misses something.</p>

<pre><code>def update(self, instance, validated_data):
    instance.nr = validated_data.get('nr', instance.nr)
    instance.title = validated_data.get('title', instance.title)
    instance.save()

    # up till here everything is updating, however the problem appears here.
    # I don't know how to get the right InvoiceItem object, because in the validated
    # data I get the items queryset, but without an id.

    items = validated_data.get('items')
    for item in items:
        inv_item = InvoiceItem.objects.get(id=?????, invoice=instance)
        inv_item.name = item.get('name', inv_item.name)
        inv_item.price = item.get('price', inv_item.price)
        inv_item.save()

    return instance
</code></pre>

<p>Any help would be really appreciated.</p>
