[Fixed]-Django REST: Creating db entries in related table in one POST

1👍

Yes. I’m going to use the non-accepted answer from this question.

The Django docs state that you need to save the dependent model (A, in your case), before you can save the related model (B, in your case.)

Note that you must save an object before it can be assigned to a
foreign key relationship. For example, creating an Article with
unsaved Reporter raises ValueError:

>>> r3 = Reporter(first_name='John', last_name='Smith', email='john@example.com')
>>> Article.objects.create(headline="This is a test", pub_date=date(2005, 7, 27), reporter=r3)
Traceback (most recent call last):
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.

As the other answer says – you can either do this in two POSTs or handle it in the view. It’s hard to give specifics without seeing your view code, but the DRF docs have this covered.

I’ve adapted Robert’s code for use here. If it was an accepted answer, I’d just have linked it as a duplicate.

class ASerializer(serializers.ModelSerializer):                          
   class Meta:
        model = ModelA
        fields = ('field1', 'field1')


class BSerializer(serializers.ModelSerializer):
    bclass = ASerializer()
    class Meta:
        model = ModelB
        fields = ('field1', 'field2', 'etc')

views.py

import generics

class BCreateAPIView(generics.CreateAPIView):
    model = ModelB
    serializer_class = BSerializer

Leave a comment