首页 > 解决方案 > 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.

标签: pythondjangodjango-models

解决方案


首先,您需要创建用户。

u1 = User(username='user1')

u1.save()

创建用户配置文件。将“父”对象的 ID 作为该对象的 ID 传递:

v1 = UserProfile(user=u1, ....)
v1.save()

参考这个


推荐阅读