python - How to insert data into a relational one to one table in django?
问题描述
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)
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()
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.
解决方案
首先,您需要创建用户。
u1 = User(username='user1')
u1.save()
创建用户配置文件。将“父”对象的 ID 作为该对象的 ID 传递:
v1 = UserProfile(user=u1, ....)
v1.save()
参考这个
推荐阅读
- javascript - 将 Javascript 插件导入 Laravel 以在 Vue 中使用
- javascript - 如何将参数从 ES6 中的包装函数传递给函数
- wordpress - 联系表格 7 在底部显示巨大的空白区域
- azure - 下游调度程序启动中具有多个下游活动缓慢的 Azure 数据工厂管道
- javascript - 什么时候不调用反应计时器组件,但影响所有其他打开的组件?
- android - Android:WRAP_CONTENT 不适用于 layout_toStartOf
- qt - ARM 的 Qt 交叉编译
- python - Python 获取原始输入并在包含多个字符的一行中搜索它
- php - 在自定义 style.css 文件中的一些更改时,它没有显示 wordpress“[...]”中帖子页面的完整内容
- c - 使用 C 语言 (Linux) 在后台运行睡眠