Not null constraint failed in create method of nested serializer

240 views Asked by At

I'm trying to create an apiview to add data of a nested json in the database. The models are:

class Catch(models.Model):
    haul = models.ForeignKey('hauls.Haul')
    weight = models.IntegerField()
    category = models.ForeignKey('species.Category')


class Sex(models.Model):
    catch = models.ForeignKey('catches.Catch', related_name='sexes')
    sex = models.IntegerField()
    
    
class Length(models.Model):
    sex = models.ForeignKey('samples.Sex', related_name='lengths')
    length = models.IntegerField()
    number_individuals = models.IntegerField()

The JSON I try to store in database is:

{
    "catch_id":"6125",
    "sex":"2",
    "lengths": [
        {
            "catch_id":"6125",
            "length": 24,
            "number_individuals": 1
        },
        {
            "catch_id":"6125",
            "length": 25,
            "number_individuals": 1
        },
        {
            "catch_id":"6125",
            "length": 26,
            "number_individuals": 1
        }
]
}

And the serializers involved are:

class LengthSerializer(serializers.ModelSerializer):

    class Meta:
        model= Length
        fields = ['sex_id', 'length', 'number_individuals',  ]
        
        
class SexCatchSerializer (serializers.ModelSerializer):

    lengths = LengthSerializer(many=True)

    class Meta:
        model = Sex
        fields = ['id', 'sex', 'catch_id', 'lengths', ]

    # This is a nested serializer, so we have to overwrite the create function
    def create(self, validated_data):
        # Firstly, get the data from the nested parts
        lengths_data = validated_data.pop('lengths')
        # Secondly, save the Sex
        sex = Sex.objects.create(**validated_data)
        # Then, save the nested parts in its own models
        Length.objects.create(sex=sex, **lengths_data)
        # And finally, return the sex
        return sex
    

But an error django.db.utils.IntegrityError: NOT NULL constraint failed: samples_sex.catch_id is returned in sex = Sex.objects.create(**validated_data) and I can't figure out why if the catch_id field is in the JSON and obviously is not null.

0

There are 0 answers