当前位置:网站首页>DRF receives nested data and creates objects. Solution: DRF not NULL constraint failed

DRF receives nested data and creates objects. Solution: DRF not NULL constraint failed

2022-06-12 21:26:00 Love letter from Ali

One 、 A reproduction of the scene

I set up a userinfo surface , And foreign key connection user surface , stay serializers Class implements forward nesting , My goal is to receive the user's json Data is automatically created UserInfo object , And save it in the database .

I put out the configuration information , This is a factor that may affect the operation of the program :
Django 4.0.3 4.0.4
django-filter 21.1 21.1
djangorestframework-simplejwt 5.2.0 5.2.0
django-cors-headers 3.12.0 3.12.0
djangorestframework 3.13.1 3.13.1

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } }

Two 、 The scene of the accident

models.py

class UserInfo(models.Model):
    personInfo = models.ForeignKey(User, on_delete=models.CASCADE)
    days = models.IntegerField()
    progress = models.IntegerField()
    pub_date = models.DateTimeField('date published', null=True)
    recitation = models.ManyToManyField(to='Word', verbose_name=' Memorized words ', null=True)

serializers.py

class UserInfoSerializer(serializers.ModelSerializer):
    personInfo = UserSerializer()

    class Meta:
        model = UserInfo
        fields = ['personInfo', 'days', 'progress', 'pub_date', 'recitation']

    def create(self, validated_data):
        profile_data = validated_data.pop('personInfo')
        userinfo = UserInfo.objects.create(**validated_data)
        User.objects.create(personInfo=userinfo, **profile_data)
        return userinfo

3、 ... and 、 Check official documents

Official about writing for nested method create Examples of methods

Writing .create() methods for nested representations
If you’re supporting writable nested representations you’ll need to write .create() or .update() methods that handle saving multiple objects.

The following example demonstrates how you might handle creating a user with a nested profile object.

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ['username', 'email', 'profile']

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = User.objects.create(**validated_data)
        Profile.objects.create(user=user, **profile_data)
        return user

Four 、 Problem solving

Maybe the official website document is different from my situation , Maybe it used jwt Why .
Report errors :NOT NULL constraint failed

Send the official website documents to create Methods user = User.objects.create(**validated_data) This line is changed to :user_obj, created = User.objects.get_or_create(**user_dict) solve .

Corrected code :

models.py

class UserInfo(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    days = models.IntegerField()
    progress = models.IntegerField()
    pub_date = models.DateTimeField('date published', null=True)
    recitation = models.ManyToManyField(to='Word', verbose_name=' Memorized words ', null=True)

    def __str__(self):
        return self.user.username

    class Meta:
        ordering = ['pub_date']

serializers.py

class UserInfoSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = UserInfo
        fields = ['user', 'days', 'progress', 'pub_date', 'recitation']

    def create(self, validated_data):
        user_dict = validated_data.pop('user')
        user_obj, created = User.objects.get_or_create(**user_dict)
        return UserInfo.objects.create(user=user_obj, **validated_data)

原网站

版权声明
本文为[Love letter from Ali]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206122122522548.html