简体   繁体   English

Django无法保存与User表相关的数据。 它说它没有`mymodel_set`属性

[英]Django is failing to save data related to User table. It says it doesn't have `mymodel_set` attribute

I have a model linked to Django User model but when I try saving to that model using User instance, it says 'User' object has no attribute 'mymodel_set' 我有一个链接到Django User模型的模型,但是当我尝试使用User实例保存到该模型时,它说'User'对象没有属性'mymodel_set'

My models.py: 我的models.py:

from django.contrib.auth.models import User
from django.db import models

class MyModel(models.Model):
    user = models.OneToOneField(User, blank=True, null=True, related_name='mymodel')
    name = models.CharField(max_length=14, blank=True, null=True)

My views.py: 我的views.py:

from django.contrib.auth.models import User
from myapp.models import mymodel

def register(request):
    #gets data here from template
    user = User(username=reg_username, password=reg_password)
    user.save()
    user.mymodel_set.create(name= display_name)
    return HttpResponse('Success')

If the related object existed, you would use mymodel , but it does not exist and the relationship is void, so it cannot be accessed via the user . 如果相关对象存在,则可以使用mymodel ,但它不存在并且关系为空,因此无法通过user访问。 Create it first and set the relationship to that user: 首先创建它并设置与该用户的关系:

mymodel = MyModel.objects.create(name=display_name, user=user)
#                                                   ^^^^ set related user

The _set suffix is usually used for reverse ForeignKey relationships and not for OneToOne relationships. _set后缀通常用于反向的ForeignKey关系,而不用于OneToOne关系。

Also note that the related_name on the user field was already specified as mymodel , and the related field can now be accessed from the User model via user.mymodel 还要注意的是related_name用户现场已经被指定为mymodel ,以及相关的领域,现在可以从访问User通过模型user.mymodel

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

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