Django rest framework - filter many-to-many field

后端 未结 2 956
孤街浪徒
孤街浪徒 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..

    0 讨论(0)
  • I have found a other Stackoverflow question that has a solution that could be used here:

    How can I apply a filter to a nested resource in Django REST framework?

    (see under the "Solution" headline in the question itself)

    0 讨论(0)
提交回复
热议问题