jarmod
jarmod

Reputation: 78663

DRF create record with multiple child records in same POST

I am using django-rest-framework 3.3.1 and am struggling to deserialize a new record and related records in the same POST.

My models look like this:

class Employee(models.Model):
    name = models.CharField(max_length=128)
    locn = models.CharField(max_length=128)

class Degree(models.Model):
    employee = models.ForeignKey(Employee, related_name='degrees')
    type = models.CharField(max_length=128)
    date = models.DateField()

I have a simple serializer for the degree:

class DegreeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Degree
        fields = ('id', 'employee', 'type', 'date',)

and a simple employee serializer:

class EmployeeSerializer(serializers.ModelSerializer):
    degrees = DegreeSerializer(many=True)

    class Meta:
        model = Employee
        fields = ('id', 'name', 'locn', 'degrees',)

I want the user to be able to add the new employee and his degrees in the same UI dialog (rather than add the employee first then later add degrees to the now-existing employee). My attempts to put both a new Employee and new Degrees in the same POST fails with DRF telling me that employee is required on the degree items. Is it possible to do this natively in DRF?

A related question is how do you ensure that when the user issues a PUT on the Employee with modified Degree items that those degree items actually replace all of the existing items in the DB?

Thanks.

Upvotes: 2

Views: 668

Answers (1)

levi
levi

Reputation: 22697

You need to deal with nested object creation. By default, is not supported, you need to rewrite create() and update() methods from your serializers.

Here, there is an example from DRF docs

Upvotes: 2

Related Questions