Django rest framework - filter many-to-many field

后端 未结 2 1001
孤街浪徒
孤街浪徒 2021-01-18 23:02

Suppose I have a model like this one:

class Car(models.Model):
    images = models.ManyToManyField(Image)

class Image(models.Model):
    path = models.CharF         


        
2条回答
  •  忘掉有多难
    2021-01-18 23:14

    I don´t know if you are still looking for this answer, but maybe it helps someone else.

    First create a filter class like this:

    class CarFilter(django_filters.FilterSet):
        having_image = django_filters.Filter(name="images", lookup_type='in')
    
        class Meta:
            model = Car
    

    Then add the filter to your view:

    class CarList(generics.ListAPIView):
        model = Car
        serializer_class = CarSerializer
        filter_class = CarFilter
    

    And that´s all. Add "?having_image=1" to your query string and Django filter should do the trick for you.

    Hope it helps..

提交回复
热议问题