当前位置:网站首页>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)
边栏推荐
- Allegro Xile technology, a developer of distributed cloud services, received millions of dollars of angel round financing and was independently invested by Yaotu capital
- Data visualization - broken line area chart
- Can flush open an account? Can you directly open the security of securities companies on the app
- #886 Possible Bipartition
- Teambition 协作应用心得分享|社区征文
- 冒泡排序
- 风控建模十:传统建模方法存在的问题探讨及改进方法探索
- RestTemplate的@LoadBalance注解
- Compréhension préliminaire des expressions régulières cognitives (regex)
- The year of the outbreak of financial innovation! All dtinsight products of kangaroo cloud data stack have passed the special test of Xinchuang of ICT Institute
猜你喜欢

Data visualization - histogram

NIO使用指南

Teambition 协作应用心得分享|社区征文

Test basis: unit test

Data visualization diagram microblog forwarding diagram

金融信创爆发年!袋鼠云数栈DTinsight全线产品通过信通院信创专项测试

Lombok package is successfully installed, but the runtime prompts that get, set method and constructor solution cannot be found

The salted fish has been transmitted for 5W times, and the latest spring recruit face-to-face test questions of bytes have been leaked

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

String Basics
随机推荐
金融信创爆发年!袋鼠云数栈DTinsight全线产品通过信通院信创专项测试
Shell script Basics
zgc的垃圾收集的主要阶段
Access control system based on RFID
Experiment 7-2-6 print Yanghui triangle (20 points)
Recursively call knowledge points - including example solving binary search, frog jumping steps, reverse order output, factorial, Fibonacci, Hanoi tower.
Oracle 19c 安装文档
Inrelease: the following signature cannot be verified because there is no public key: no_ PUBKEY EB3E94ADBE1229CF
初步了解认识正则表达式(Regex)
Compréhension préliminaire des expressions régulières cognitives (regex)
Sorting out the knowledge points of primary and secondary indicators
Ubuntu 16.04 installing mysql5.6
GNS安装与配置
JS deep and shallow copy
[leetcode] 573 complex multiplication (conversion between characters and numbers)
Cv2.lut() (populates the output array with values from the lookup table)
Solution of multi machine room dynamic loop status network touch screen monitoring
Pixel level reconstruction and restoration technology to solve severe image blur
leetcode:210. Schedule II
China hydraulic press market trend report, technical innovation and market forecast