1

「アカウント」と「myapp」の2つのアプリがあります。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(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])

このブログ投稿の最後の行に注意してください。これにより、次のような方法でユーザープロファイル情報にアクセスできます。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 / 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)

「/homepage/でNameError、グローバル名'user'が定義されていません」というメッセージが表示されます。これは、各Teacherオブジェクトのteacher.userプロパティに正しくアクセスしていないためだと思いますが、間違っている可能性があります。

私は関係を逆トラバースするあらゆる種類の組み合わせを試しました:

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

しかし、上記の多くは「/ homepage /キーワードのSyntaxErrorは式にはなり得ない」と言っているので、現在の化身はおおよそ正しいと思います。

奇妙なことに、フィルターの右側は正常に機能しているようです(= request.user.profile.organisation一部)

4

1 に答える 1

5

関係にまたがるクエリルックアップに関するドキュメントは非常に有益です。認識すべきことは、これは標準関数であるため、左側は常に式ではなく単一のキーワードである必要があるということです。これを有効にするには、二重アンダースコア構文を使用します。

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

また、これは単一であることに注意してください。これ=も、式ではなく関数の呼び出しです。

于 2012-03-05T20:07:57.043 に答える