R
R
Radist_1012015-12-11 08:34:24
Django
Radist_101, 2015-12-11 08:34:24

How to properly filter a queryset between many-to-many fields using django-filter?

There are three models:

class Car(models.Model):
     sub_types = models.ManyToManyField(SubType)

class SubType(models.Model):
     types = models.ManyToManyField(Type)

class Type(models.Model):
     pass

It is necessary to filter entries in the Car model using django-rest-framework via get parameters, here is the code I wrote:
class CarFilter(django_filters.FilterSet):
    type = django_filters.MethodFilter(action='type_filter')
    class Meta:
        model = Car
        fields = ['sub_type',  'type']

    def type_filter(self, queryset, value):
        sub_types = list(SubType.objects.filter(types__id=value).values_list('id', flat=True))
        cars = queryset.filter(sub_types__in=sub_types)
        return cars

class CarsList(generics.ListAPIView):
    renderer_classes = (renderers.JSONRenderer,)

    model = Car
    queryset = Car.objects.all()
    serializer_class = CarSerializer
    filter_backends = (filters.DjangoFilterBackend, )
    filter_class = CarFilter

I'm interested in this piece of code:
sub_types = list(SubType.objects.filter(types__id=value).values_list('id', flat=True))
cars = queryset.filter(sub_types__in=sub_types)

Can this part be optimized?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question