如何过滤使用扩展模型 class 字段连接的活跃用户

How to filter active users connected using an extended model class field

我已经使用 OneToOne 关系将用户模型扩展为模型 class 'Student'。现在我想用 'Student' class 中的字段过滤所有活跃学生,例如 'name'.

在 django 中尝试过 shell:

Student.objects.filter(user.is_active == True)
Traceback (most recent call last):
 File "<console>", line 1, in <module>
NameError: name 'user' is not defined

我的看法:

def entry(request):
     user = request.user
     if request.user.is_active:
        print("Already logged in")
        return redirect('home')
     else:
        return render (request, 'entry.html')

我的模特:

class Student(models.Model):
     name = models.CharField(max_length=200)
     branch = models.CharField(max_length=200, choices=BRANCHES)
     sem = models.CharField(max_length=200, choices=SEMESTERS)
     reg_no = models.CharField(max_length=200, unique = True)
     balance = models.IntegerField(default=0)
     pin_no = models.CharField(max_length=200, unique = True)
     college = models.ForeignKey(Institute, on_delete=models.CASCADE )
     user = models.OneToOneField(User, on_delete=models.CASCADE)```

您可以过滤:

Student.objects.filter(<b>user__is_active=True</b>)

或者如果您想 RetrieveStudent 模型链接到登录用户,并且该用户应该处于活动状态,您可以使用:

Student.objects.filter(<b>user=request.user,</b> user__is_active=True)

如果用户不是学生,或者如果用户 未激活。

你可以通过这个为request.user对象稍微提高效率,所以:

if request.user<b>.is_active</b> and Student.objects.filter(user=request.user)<b>.exists()</b>:
    # user is a student and the user account is active
    pass