「アカウント」と「myapp」の2つのアプリがあります。request.userと同じ組織に属する教師オブジェクトのみをビューに表示しようとしています。
account / models.pyfrom 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
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
一部)