Search code examples
djangodjango-modelsdjango-querysetdjango-users

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


I have extended the user model to a model class 'Student' using OneToOne relation. Now I want to filter all active students with a field in the 'Student' class such as 'name'.

Tried this in 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

my View:

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

my Models:

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)```

Solution

  • You can filter with:

    Student.objects.filter(user__is_active=True)

    or if you want to Retrieve the Student model linked to the logged in user, and that user should be active, you can work with:

    Student.objects.filter(user=request.user, user__is_active=True)

    This will return an empty QuerySet if the user is not a student, or if the user is not active.

    You can boost the efficiency slighly by this for the request.user object, so:

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