0

我正在尝试在 Django Admin 中执行自定义过滤器,但在我的情况下,当我根据父母和老师进行过滤时,我倾向于得到重复的值。意思是说父母的数量(481)多于总数(221)。有些值会重复。我该如何避免这种情况?任何的想法?

管理员.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')

模型.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)

在这方面需要一些指导......

4

1 回答 1

3

同一个学生必须存在多个关系;假设有 3 个成人角色的P学生将返回 3 个学生;您必须distinct()向您的电话添加电话QuerySet以确保学生是唯一的。

于 2012-08-27T05:23:17.287 回答