Search code examples
pythondjangoforeign-keysmodels

how to access database model fields of parent model linked as e.g. Class->School->User?


I am fairly new to programming languages, django and database models. So my question is simple I have 3 models in models.py as

class UserProfileInfo(models.Model):
# create relationship with built-in user in admin
user = models.OneToOneField(User)
portfolio_site = models.URLField(blank=True)

class School(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=256)
principal = models.CharField(max_length=256)
location = models.CharField(max_length=256)

class Classroom(models.Model):
school = models.ForeignKey(School, on_delete=models.CASCADE)
class_name = models.CharField(max_length=256)
desc = models.CharField(max_length=256)

And I want to access 'id' from User model. I have tried using

def ClassroomView(request):

classroom_list = Classroom.objects\
                    .filter(school__id=request.session.get('user_id','0'))\
                    .filter(user__id=1).values()
class_dict = {'class_records': classroom_list}
return render(request, 'basic_app/classroom_list.html', context=class_dict)

And it gives the following error:

FieldError at /basic_app/class/
Cannot resolve keyword 'user' into field. Choices are: class_name, desc, id, school, school_id

Is there any way that i can access the fields of User model from Classroom model since it is linked by foreign key as Classroom->School->User Please tell me if I am doing something wrong here any insights and solutions are appreciated!!


Solution

  • Just to recap:

    • User - UserProfileInfo = 1:1
    • School - User = 1:N
    • Classroom - School = 1:N

    In other words each user has 1 and only one UserProfile. Each school has 1 user attached and that user can be attached to multiple schools (not sure if this is desired, but that depends on the use case). Each school can have multiple classrooms.

    Your goal is to return the list of schools attached to the user. I would do this by:

    classroom_list = Classroom.objects.filter(school__user=User.objects.get(pk=0))
    

    or if in a view with request:

    classroom_list = Classroom.objects.filter(school__user=request.user)