将对象数组传递给另一个模型调用djano

时间:2017-01-24 02:25:21

标签: python django database models

我正在尝试为用户选择所有类,然后加载所有对应的类对象。这是我的model.py文件:

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)

以下是我正在制作的电话:

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)

我如何实现上述目标?

1 个答案:

答案 0 :(得分:0)

你可以做到

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

现在classes个对象包含用户所属的所有类。