重复导致Django管理员中的自定义列表过滤

时间:2012-08-27 04:23:36

标签: django django-admin

我正在尝试在Django Admin中执行自定义过滤器,但似乎当我在我的情况下根据父级和教师进行过滤时,我倾向于获得重复的值。意思是说父母的数量(481)大于总数(221)。一些价值观重复了......我该如何避免这种情况?有什么想法吗?

admin.py:

class AdultRoleListFilter(SimpleListFilter):

    title = _('Role of Adult')
    parameter_name = 'adultrole'
    def lookups(self, request, model_admin):
        return (
            ('T', _('Teacher')),
            ('P', _('Parent')),)
    def queryset(self, request, queryset):
        if self.value() == 'P':
            return queryset.filter(relationships__role='P')
        if self.value() == 'T':
            return queryset.filter(relationships__role='T')

Models.py

class Student(models.Model):
   name = models.CharField(max_length=255)
   birthday= models.DateField(blank=True,null=True)

class Adult(models.Model):
   user = models.OneToOneField(User)
   students = models.ManyToManyField(Student, through='StudentAdultRelationship', related_name='adults')

class class StudentAdultRelationship(models.Model):

    PARENT = 'P'
    TEACHER ='T'
    FOLLOWER = 'F'

    ROLE_CHOICES = (
        (PARENT, 'Parent'),
        (TEACHER, 'Teacher'),
        (FOLLOWER, 'Follower'),
    )

    adult = models.ForeignKey(Adult, related_name='relationships')
    student = models.ForeignKey(Student, related_name='relationships')
    role = models.CharField(choices=ROLE_CHOICES, max_length=1)

需要一些指导......

1 个答案:

答案 0 :(得分:3)

同一个学生必须存在多种关系;比如说一个有3名角色P成年人的学生将返回3名学生;您必须向distinct()添加QuerySet来电,以确保您找到独特的学生。