简体   繁体   English

Django 与用户的一对一关系不使用查询

[英]Django onetoone relationship with User not working with query

My model is like this我的模型是这样的

class Profile(models.Model):
    user = models.OneToOneField(User,default=None,null=True,on_delete=models.CASCADE)
    name = models.CharField(max_length=50,null=True)

i am trying to get through models using shell but getting the empty query.我正在尝试使用 shell 通过模型但得到空查询。 I tried this我试过这个

>>> u1=User.objects.get(username='gautam')
>>>u1
<User: gautam> 
>>> Profile.objects.get(user=u1)
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/home/gautam/.local/lib/python3.6/site- 
packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/gautam/.local/lib/python3.6/site- 
packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
homes_login.models.DoesNotExist: Profile matching query does not 
exist.

I am tring to get the user for that profile.我正在尝试获取该个人资料的用户。

This profile is simply not created.这个配置文件根本就没有创建。 Setting an OneToOne relation doesn't guarantee that profile will exist for each user.设置OneToOne关系并不能保证每个用户都存在配置文件。 To overcome that, you should simply create new profile, like this:为了克服这个问题,您应该简单地创建新的配置文件,如下所示:

>>> Profile.objects.create(user=u1)

To automate process of getting existing profile or creating new one, you can use get_or_create method.要自动化获取现有配置文件或创建新配置文件的过程,您可以使用get_or_create方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM