如何在Django的一对一关系表中插入数据? [英] How to insert data into a relational one to one table in django?
问题描述
我有一个 UserProfile
表,该表与默认的Django User
表相关。这是它的外观。
I have a UserProfile
table which is in relation with the default Django User
table. Here's how it looks.
class UserProfile(models.Model):
user = user.OneToOneField(User, on_delete=models.CASCADE)
section = models.CharField(max_length=255, blank=True)
year = models.IntegerField(null=True, blank=True)
course = models.CharField(max_length=255, blank=True)
qrcode = models.CharField(max_length=255, blank=True)
present = models.BooleanField(default=False)
我正在尝试使用 Django Shell
将数据插入UserProfile表中。
I am trying to insert the data into the UserProfile table using the Django Shell
.
from users.models import UserProfile
a = UserProfile(qrcode="hello")
a.save()
这就是我一直知道的将数据插入表中的方式,一直都在工作。但是,当我尝试在 UserProfile
模型中执行此操作时。我得到这个例外。 NOT NULL约束失败:users_userprofile.user_id 。这又是由以下异常格式错误引起的:RelatedObjectDoesNotExist:UserProfile没有用户。
This is how I have always known to insert data into tables, it has always worked. BUT when i try to do this in UserProfile
model. I get this exception. NOT NULL constraint failed: users_userprofile.user_id. Which in turn is caused by the following exception Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user.
我有点理解我需要以某种方式提供一个用户实例。但是我对如何一无所知。有人可以帮帮我吗。
I somewhat understand that I somehow need to supply a user instance. But I am clueless as to how. Can someone please help me.
推荐答案
首先,您需要创建User。
Firstly you need to create User.
u1 = User(username='user1')
u1.save()
创建一个用户配置文件。传递父对象的ID作为该对象的ID:
Create a UserProfile. Pass the ID of the "parent" object as this object’s ID:
v1 = UserProfile(user=u1, ....)
v1.save()
请参考此
这篇关于如何在Django的一对一关系表中插入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!