嵌套序列化程序的创建方法中的非空约束失败

问题描述

我正在尝试创建一个apiview以在数据库添加嵌套json的数据。 这些模型是:

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()

我尝试存储在数据库中的JSON是:

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

涉及的序列化器是:

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
    

但是在django.db.utils.IntegrityError: NOT NULL constraint Failed: samples_sex.catch_id中返回了错误sex = Sex.objects.create(**validated_data),我不知道为什么catch_id字段在JSON中并且显然不是null。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)