如何在django“admin.py”中过滤ManyToManyField表的结果?

时间:2011-02-04 08:23:08

标签: django django-admin

对不起英文不良和信息不足

# Models.py #
class Course(models.Model):
    course_code = models.CharField(max_length=100)
    title = models.CharField(max_length=200)
    short = models.CharField(max_length=50)
    elective_group = models.CharField(max_length=100)
    def __unicode__(self):
        return self.course_code

class Lecturer(models.Model):
    username = models.ForeignKey(User)
    assigned_course = models.ManyToManyField(Course)

#admin.py#
from django.contrib import admin
from mysite.question_bank.models import *


class CourseAdmin(admin.ModelAdmin):
    list_display = ('course_code', 'title', 'short' )
    def queryset(self, request):
        qs = super(CourseAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs    #(all the courses)
        else:
            return qs.filter( ????? ) # particular courses for a username

讲师可以分配尽可能多的课程。我想返回一个查询集,其中包含为特定用户名分配的课程。

1 个答案:

答案 0 :(得分:0)

  

return qs.filter( ????? )#用户名的特定课程

你可以做到

return request.user.lecturer_set.get().course_set.all()