简体   繁体   中英

Django Rest Framework filterset on many to many field

I'm trying to filter manytomany field by it's name field but I can't set it up properly. Could any body have a look at this?

Models

class Criteria(models.Model):
    name = models.CharField(max_length=400, primary_key=True)
    tests = models.ManyToManyField(Test)

class Test(models.Model):
    name = models.CharField(max_length=4000)

Views

class CriteriaViewSet(DefaultsMixin, viewsets.ModelViewSet):
    queryset = Criteria.objects.all()
    filter_class = CriteriaFilter
    filter_fields = ('tests',)


    def get_serializer_class(self):
        if self.action == 'list':
            return CriteriaSerializer
        return CriteriaDetailSerializer

Filterset

class CriteriaFilter(django_filters.FilterSet):
    test = django_filters.CharFilter(name="tests__name", lookup_type='contains')
    class Meta:
        model = Criteria
        fields = ('tests',)

Serializers

class CriteriaSerializer(serializers.ModelSerializer):
    tests = serializers.StringRelatedField(many=True)
    links = serializers.SerializerMethodField()

    class Meta:
        model = Criteria
        fields = ('name', 'tests', 'links')

    def get_links(self, obj):
        request = self.context['request']
        return {
            'self': reverse('api:criterium-detail',
            kwargs={'pk': obj.pk},
            request=request),
        }

With the configuration above what I get on the URL:

/api/criteria/?test=FB1400

is empty results array even though there is a number of Criteria containing addressed test:

HTTP 200 OK Content-Type: application/json Vary: Accept Allow: GET, POST, HEAD, OPTIONS

{
    "count": 0,
    "next": null,
    "previous": null,
    "results": []
}

I was trying different lookups (exact, in, contains) as well as different values in fields but none of those works for me... I was also wondering if I should set up django filter backend somewhere but I'm not sure how to do this and I don't know if it's necessary in this case.

Not sure if you solved it, but this post is similar to this other which was solved by the way:

Django Rest Framework (GET filter on ManyToMany field)

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM