当前位置:网站首页>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)
边栏推荐
- Delphi XE7的蓝牙 Bluetooth
- #113 Path Sum II
- Is it safe to open an account in flush? How to open an account online to buy stocks
- JS deep and shallow copy
- Pytorch how to set random number seed to make the result repeatable
- [leetcode] 573 complex multiplication (conversion between characters and numbers)
- Solution of multi machine room dynamic loop status network touch screen monitoring
- Digital intelligence data depth | Bi goes down the altar? It's not that the market has declined, it's that the story has changed
- Integrated monitoring solution for power environment of small and medium-sized computer rooms
- Product Manager: "click here to jump to any page I want to jump" -- decoupling efficiency improving artifact "unified hop routing"
猜你喜欢

My way of programming

Data visualization diagram microblog forwarding diagram

A high-value MySQL management tool

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

New product release Junda intelligent integrated environmental monitoring terminal

Access control system based on RFID

Lintcode:127. Topology sorting

#141 Linked List Cycle

torch. nn. Linear() function

Product Manager: "click here to jump to any page I want to jump" -- decoupling efficiency improving artifact "unified hop routing"
随机推荐
模块八:设计消息队列存储消息数据的MySQL表
Ubuntu16.04 completely delete MySQL database
The service did not report any errors MySQL
#886 Possible Bipartition
Market trend report, technical innovation and market forecast of hydraulic chain hoist in China
Pointer and array & pointer and const & struct and Const
Structure knowledge points all in
CUDA out of memory
插入排序
同花顺能开户吗,在同花顺开户安全么
InRelease: 由于没有公钥,无法验证下列签名: NO_PUBKEY EB3E94ADBE1229CF
EU officially released the data act, Ukraine was attacked by DDoS again, kitchen appliance giant Meiya was attacked, internal data leakage network security weekly
makefile 的ifeq,filter,strip 简单使用
Test basis: unit test
最简单ALV模板
GNS installation and configuration
#981 Time Based Key-Value Store
Lombok package is successfully installed, but the runtime prompts that get, set method and constructor solution cannot be found
#113 Path Sum II
#141 Linked List Cycle