2012-03-05 64 views
0

我有两个应用程序,“帐户”和“myapp”。我试图在视图中仅显示与request.user属于同一组织的那些教师对象。Django:遍历OneToOneField关系,访问模型的'用户'字段 - NameError

帐户/ 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(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]) 

注意最后一行,从this博客文章,可以解决一些访问用户的个人资料信息,如user.profile.organisation

的myapp/models.py
from django.contrib.auth.models import User 

class Teacher(models.Model): 
    user = models.OneToOneField(User, related_name='teacher') 
MYAPP /人次.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) 

我得到“NameError at/homepage /,全局名'user'未定义”。我认为这是因为我没有正确访问每个教师对象的teacher.user属性,但我可能是错的。

我已经试过各种穿越的关系相反的组合:

user.is_active 
user__is_active 
user.profile.organisation 
user.profile__organisation 

但许多上面给我的“在/主页的SyntaxError /关键字不能是一个表达式”,所以我觉得目前的化身大致是正确的。

奇怪的是,过滤器的右手边似乎很好地工作(在= request.user.profile.organisation部分)

回答

4

query lookups that span relationships的文档是相当翔实。要实现的是这是一个标准功能,所以左侧必须始终是单个关键字,而不是表达式。为了实现这一点,使用双下划线的语法:

Teacher.objects.filter(user__profile__organisation=request.user.profile.organisation, user__is_active = True) 

还要注意它是一个单一的= - 再次,这是一个函数调用,而不是一个表达式。

+0

谢谢。我有一种感觉,在我的问题中存在无知。我的理解错误地认为,为了跨越关系,你使用'child__parent__parent_field',但是转发它的'parent.child.child_field'。这在您链接的文档的前四段中已被揭穿,所以谢谢。虽然似乎没有使用'user.profile'技巧,所以我只需确保所有用户都有配置文件并恢复为'user__userprofile'。 – nimasmi 2012-03-06 07:36:14