Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中将数据插入到一对一的关系表中?_Python_Django_Django Models - Fatal编程技术网

Python 如何在django中将数据插入到一对一的关系表中?

Python 如何在django中将数据插入到一对一的关系表中?,python,django,django-models,Python,Django,Django Models,我有一个UserProfile表,它与默认的DjangoUser表相关。这是它的样子 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)

我有一个
UserProfile
表,它与默认的Django
User
表相关。这是它的样子

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表

from users.models import UserProfile

a = UserProfile(qrcode="hello")
a.save()
这就是我一直知道的将数据插入表的方式,它一直都是有效的。但是当我在
UserProfile
模型中尝试这样做时。我得到这个例外非空约束失败:用户\u userprofile.user\u id。而这又是由以下异常引起的:RelatedObjectDoesNotExist:UserProfile没有用户


我知道我需要提供一个用户实例。但我不知道该怎么做。谁能帮帮我吗

首先,您需要创建用户

u1 = User(username='user1')

u1.save()
创建一个用户配置文件。将“父”对象的ID作为此对象的ID传递:

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

请参阅

您需要先创建您的用户

user = User.objects.create(username='user')
然后你可以做:

user_profile = UserProfile.objects.create(user=user, ...)