当前位置:网站首页>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.4django-filter 21.1 21.1djangorestframework-simplejwt 5.2.0 5.2.0django-cors-headers 3.12.0 3.12.0djangorestframework 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)
边栏推荐
- Research Report on market supply and demand and strategy of China's hydraulic injection molding machine industry
- torch. Finfo function
- Introduction to the characteristics of balancer decentralized exchange market capitalization robot
- Is it safe to open an account in flush? How to open an account online to buy stocks
- Do we media video, and share the necessary app for friendly new media operation
- InRelease: 由于没有公钥,无法验证下列签名: NO_PUBKEY EB3E94ADBE1229CF
- torch. unique()
- 初步了解認識正則錶達式(Regex)
- leetcode:207. 课程表
- 数据批量写入
猜你喜欢

阅读笔记 Deep Hough Voting for 3D Object Detection in Point Clouds

lintcode:127 · 拓扑排序

【目标检测】|Dive Deeper Into Box for Object Detection 基于FCOS新训练方法

leetcode:210. Schedule II

My way of programming

Leetcode: 210. Programme II

C language learning notes (II)

Structure knowledge points all in

leetcode:210. 課程錶 II

Pixel level reconstruction and restoration technology to solve severe image blur
随机推荐
leetcode:210. 課程錶 II
gzip压缩解压缩
#981 Time Based Key-Value Store
Simplest ALV template
How to design a message box through draftjs
USB机械键盘改蓝牙键盘
ATOI super resolution
GPU giant NVIDIA suffered a "devastating" network attack, and the number one malware shut down its botnet infrastructure | global network security hotspot on February 28
指针与数组&指针与const&结构体与const
torch. nn. Linear() function
Fill in the checklist & lt; int> Have default values? [repeat] - fill list & lt; int> with default values? [duplicate]
Redis cluster mget optimization
好数对的求解
atoi超强解析
Junda technology is applicable to "kestar" intelligent precision air conditioning network monitoring
Research Report on hydraulic injection machine industry - market status analysis and development prospect forecast
torch. clamp_ min_ method
数据批量写入
#981 Time Based Key-Value Store
Data visualization - histogram