pythondjangomodelattribute

Querying related model-attributes in django


I have the following custom user model arrangement.

```
class User(AbstractUser):
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)

class StudentProfile(models.Model):
    student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    location = models.CharField(max_length=8, blank=False, default='')
class TeacherProfile(models.Model):
    teacher = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    location = models.CharField(max_length=8, blank=False, default='')
    gender = models.CharField(max_length=8, choices=GENDER_CHOICES, default='')

```

I am able to a query the students based on the location of their teacher (current user).

Student.objects.filter(location=request.user.teacher.location)

I can also query the user model & find all teachers/students

    User.objects.filter(is_teacher=True)

QUESTION: Without relying on the profile models (Student & Teacher) How can I extend the query on abstractuser using profile attributes.

[X]-This is wrong but the idea is something like;

    User.objects.filter(is_teacher=True).filter(is_teacher.location=newyork)

Solution

  • You can follow the OneToOneField in reverse:

    User.objects.filter(teacherprofile__location='newyork')

    You thus do not need to store is_teacher and is_student explicitly. You can simply filter Students with:

    # Users with a related StudentProfile record
    User.objects.filter(studentprofile__isnull=False)