0

I am trying to select all class for a user and then load all of the classes objects that are corresponding. Here is my model.py file:

from django.db import models
from django.contrib.auth.models import User


class Class(models.Model):
    name = models.CharField(max_length=150)
    description = models.TextField()
    teacher = models.ForeignKey(User)

class UserClasses(models.Model):
    class_name = models.ForeignKey(Class)
    user = models.ForeignKey(User)

And here is the call i'm making:

def index(request):
    #grab all classes for a user
    users_classes = UserClasses.objects.filter(user=request.user)
    #pass the array of class objects and get their info
    classes = Class.objects.select_related(self=users_classes)

     context_dict = {}

     return render(request, 'dashboard/index.html', context_dict)

How can I achieve the above?

GiftZwergrapper
  • 2,602
  • 2
  • 20
  • 40
Sam Munroe
  • 1,266
  • 2
  • 20
  • 41
  • http://stackoverflow.com/questions/12281965/django-foreign-key-relation-in-template i think this question help you – Vivek Jan 24 '17 at 02:43

1 Answers1

0

You can do

users_classes = UserClasses.objects.filter(user=request.user)
classes = Class.objects.filter(class_name__in=users_classes)

Now classes objects contains all class which user belongs to.

ittus
  • 21,730
  • 5
  • 57
  • 57
  • I got the error: Cannot resolve keyword 'class_name' into field. Choices are: description, id, name, teacher, teacher_id, userclasses – Sam Munroe Jan 24 '17 at 03:35
  • Your Class model doesn't have any field `class_name` its `name` so update query like `classes=Class.objects.filter(name__in=users_classes)` – Darshit Jan 24 '17 at 03:40