当前位置:网站首页>drf 接收嵌套数据并创建对象, 解决:drf NOT NULL constraint failed
drf 接收嵌套数据并创建对象, 解决:drf NOT NULL constraint failed
2022-06-12 21:23:00 【阿狸的情书】
一、情景再现
我建立一个userinfo
表,并且外键连接user
表,在serializers
类中实现了正向嵌套,我目的是想接收用户的json
数据实现自动创建UserInfo
对象,并保存到数据库中。
我将配置信息放出来,这是可能影响程序运行的因素: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', } }
二、事故现场
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='已背单词', 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
三、查官方文档
官方关于为嵌套法写create
方法的例子
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
四、问题解决
可能是官网文档和我的情况不太一样,也许是用了jwt的原因。
报错:NOT NULL constraint failed
将官网文档给的create
方法中的user = User.objects.create(**validated_data)
这一行改为:user_obj, created = User.objects.get_or_create(**user_dict)
解决。
改正后的代码:
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='已背单词', 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)
边栏推荐
- How to improve communication efficiency during home office | community essay solicitation
- Can tonghuashun open an account? Can tonghuashun directly open the security of securities companies on the app? How to open an account online when buying stocks
- JS deep and shallow copy
- Pointer and array & pointer and const & struct and Const
- Vs2017 environmental issues
- lintcode:127 · 拓扑排序
- #113 Path Sum II
- Is it safe to open an account in flush? How to open an account online to buy stocks
- RestTemplate的@LoadBalance注解
- Structure knowledge points all in
猜你喜欢
leetcode:210. Schedule II
shell语言
Teambition 协作应用心得分享|社区征文
#113 Path Sum II
Digital intelligence data depth | Bi goes down the altar? It's not that the market has declined, it's that the story has changed
The required books for software testers (with e-books) recommended by senior Ali have benefited me a lot
In the spring recruitment of 2022, the test engineer will have a full set of interview strategies to thoroughly understand all the technical stacks (all dry goods)
Distributed cloud service developer'allegro Xile technology 'received an angel round financing of US $3million
测试基础之:单元测试
EU officially released the data act, Ukraine was attacked by DDoS again, kitchen appliance giant Meiya was attacked, internal data leakage network security weekly
随机推荐
What are the disadvantages of bone conduction earphones? Analysis of advantages and disadvantages of bone conduction earphones
Ubuntu 16.04 installing mysql5.6
初步了解认识正则表达式(Regex)
To understand Devops, you must read these ten books!
leetcode:207. Class Schedule Card
风控建模十:传统建模方法存在的问题探讨及改进方法探索
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
Understanding of functions
Select sort
Market trend report, technical innovation and market forecast of hydraulic torque wrench in China
Data visualization diagram microblog forwarding diagram
Bubble sort
Lombok package is successfully installed, but the runtime prompts that get, set method and constructor solution cannot be found
Solution of multi machine room dynamic loop status network touch screen monitoring
Preliminary understanding of regular expressions (regex)
Fill in the checklist & lt; int> Have default values? [repeat] - fill list & lt; int> with default values? [duplicate]
HR SaaS unicorn is about to emerge. Will the employee experience be the next explosive point?
Research Report on hydraulic solenoid valve industry - market status analysis and development prospect forecast
leetcode:207. 课程表