lakshmen
lakshmen

Reputation: 29084

Repeated results in Custom List Filtering in Django admin

I am trying to perform the custom filters in Django Admin but it seems that when i filter based on parent and teacher in my case, i tend to get repeated values. Meaning to say that the number of parents(481) is more than the total number(221). Some of the values get repeated.. How do i avoid this? Any idea?

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)

Need some guidance on this....

Upvotes: 0

Views: 382

Answers (1)

Multiple relationships must exist for the same student; say a Student with 3 adults of role P would return 3 students; you must add a distinct() call to your QuerySet to ensure unique students.

Upvotes: 3

Related Questions