Filtering many2many django rest framework

Viewed 31

I have an entity model, and i want to list all the instances of Entity based on the id of a category instance in it. So basically i'd like to list all the Entity instances with category id of 1 with /specialists/category/1 but for some reason i get

Not Found: /api/v1/specialists/categories/1

Even though the code looks alright.

class Entity(models.Model):
    entity_category = models.ManyToManyField(Category)


class SpecialistSerializer(serializers.ModelSerializer):
    entity_category = SpecialistCategorySerializer(read_only=True, many=True)

    class Meta:
        model = Entity
        fields = (....., entity_category)


class SpecialistsPerCategory(generics.ListAPIView):
    serializer_class = SpecialistSerializer

    def get_queryset(self):
        category_id = self.kwargs['pk']
        return Entity.objects.filter(entity_category=category_id, lookup_type='in')
    path('specialists/category/<int:pk>', SpecialistsPerCategory.as_view()),

Do you have any idea what's wrong?

1 Answers

You have category in path, but plural categories in url.

Also I think that will not work, because SpecialistSerializer have model of Entity, but you want to get pk of Category in SpecialistsPerCategory that is based on that serializer.

Related