Skip to content

Duplicate results of ManyToManyField when using SearchFilter. #1488

Closed
@yuxuan

Description

@yuxuan

I have two models:

class Course(models.Model):
    name = models.CharField(max_length=255)

class Teacher(models.Model):
    name = models.CharField(max_length=255)
    courses = models.ManyToManyField('schools.Course')

The serializer are:

class CourseSerializer(serializers.ModelSerializer):
    teacher_set = serializers.PrimaryKeyRelatedField(many=True)
    class Meta:
        model = Course

class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher

and the views for courses and teachers:

class TeacherViewSet(ModelViewSet):
    serializer_class = TeacherSerializer
    queryset = Teacher.objects.all()
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('courses',)

class CourseViewSet(StaffRequiredMixin, ModelViewSet):
    serializer_class = CourseSerializer
    queryset = Course.objects.all()

After I create a course and a teacher, when I am adding the teacher to that course and do get list of teachers, it is returning me two exactly same teacher objects.
I found that is because filter in the TeacherViewSet. If I remove filter, it is giving me correct result. I was using django-filter version 0.7. When I changed to django-filter version 0.5.4. It is working fine then.
Is that a bug of version 0.7?

Edit:

What I did was:
I created two courses (c1 and c2), then created a teacher (t1). Then I added t1 into c1. When do GET /api/teachers, I get t1 object, that's right. If add t1 into c2 and GET /api/teachers again, I will get two t1 objects.

That won't happen if I put in OrderingFilter and set ordering

I am not a native English speaker, and the question I posted was not that clear. Hopefully this update can make more sense

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions