Django:遍历OneToOneField关系,访问model-NameError的'user'字段
我有两个应用程序,“帐户”和“我的应用程序”。我试图在视图中仅显示那些与request.user属于同一组织的教师对象 account/models.pyDjango:遍历OneToOneField关系,访问model-NameError的'user'字段,django,one-to-one,user-profile,nameerror,Django,One To One,User Profile,Nameerror,我有两个应用程序,“帐户”和“我的应用程序”。我试图在视图中仅显示那些与request.user属于同一组织的教师对象 account/models.py from django.contrib.auth.models import User class Organisation(models.Model): name = models.CharField(max_length=100, unique=True) is_active = models.BooleanField(
from django.contrib.auth.models import User
class Organisation(models.Model):
name = models.CharField(max_length=100, unique=True)
is_active = models.BooleanField(default=True)
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True)
organisation = models.ForeignKey(Organisation, editable=False)
is_organisationadmin = models.BooleanField(default=False)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
请注意blog post的最后一行,它允许通过user.profile.organization
myapp/models.py
from django.contrib.auth.models import User
class Teacher(models.Model):
user = models.OneToOneField(User, related_name='teacher')
myapp/views.py
from myproject.account.models import Organisation, UserProfile
from myproject.myapp.models import Teacher
from django.contrib.auth.models import User
def homepage(request):
if request.user.is_authenticated():
teachers = Teacher.objects.filter(user.profile.organisation == request.user.profile.organisation, user__is_active = True)
我得到“namererror at/homepage/,未定义全局名称‘user’”。我认为这是因为我没有正确访问每个教师对象的teacher.user属性,但我可能是错的
我尝试了各种反向遍历关系的组合:
user.is_active
user__is_active
user.profile.organisation
user.profile__organisation
但是上面提到的很多都给了我“SyntaxError at/homepage/keyword不能是一个表达式”,所以我认为当前的版本大体上是正确的
奇怪的是,过滤器的右侧似乎工作正常(request.user.profile.organization部分)上的文档信息量很大。需要了解的是,它是一个标准函数,因此左侧必须始终是一个关键字,而不是表达式。要启用此功能,请使用双下划线语法:
Teacher.objects.filter(user__profile__organisation=request.user.profile.organisation, user__is_active = True)
还请注意,它是一个单一的=
——同样,它是一个函数调用,而不是一个表达式。上的文档提供了大量信息。需要了解的是,它是一个标准函数,因此左侧必须始终是一个关键字,而不是表达式。要启用此功能,请使用双下划线语法:
Teacher.objects.filter(user__profile__organisation=request.user.profile.organisation, user__is_active = True)
还要注意,它是一个单一的
=
——同样,它是一个函数调用,而不是一个表达式。谢谢。我觉得我的问题中有点无知。我错误地理解了,我认为,要向后跨越关系,可以使用child\u parent\u parent\u field
,但向前则是parent.child.child\u field
。这在你链接的文档的前四段中被揭穿了,谢谢。似乎无法使用user.profile
技巧,因此我将确保所有用户都有配置文件,并返回到user\uu userprofile
。谢谢。我觉得我的问题中有点无知。我错误地理解了,我认为,要向后跨越关系,可以使用child\u parent\u parent\u field
,但向前则是parent.child.child\u field
。这在你链接的文档的前四段中被揭穿了,谢谢。但似乎无法使用user.profile
技巧,因此我将确保所有用户都有配置文件,并恢复到user\uu userprofile
。