0

I have list of query sets and need to connect them into one.

How to concatenate list of query sets into one?

class TagListAPIView(generics.ListAPIView):


    serializer_class = serializers.TagSerializer

    def get_queryset(self):

        search_words = self.request.query_params['search_with'].split()

        querysets = []
        for word in search_words:
            queryset = Tag.objects.filter(
                Q(name__contains = word)
            )
            querysets.append(queryset)

        return querysets # ListAPIView does not accept this
Bigair
  • 1,452
  • 3
  • 15
  • 42
  • Does this answer your question? [How to combine two or more querysets in a Django view?](https://stackoverflow.com/questions/431628/how-to-combine-two-or-more-querysets-in-a-django-view) – Ahmed I. Elsayed Mar 31 '20 at 03:41

2 Answers2

0

I don't think I pretty but I somehow managed to do it.

class TagListAPIView(generics.ListAPIView):

    serializer_class = serializers.TagSerializer

    def get_queryset(self):

        search_words = self.request.query_params['search_with'].split()

        querysets = Tag.objects.none() # 1. Prepare empty queryset
        for word in search_words:
            queryset = Tag.objects.filter(
                Q(name__contains = word)
            )
            querysets = querysets.union(queryset) # 2. Use union

        return querysets
Bigair
  • 1,452
  • 3
  • 15
  • 42
0

Rather than using the __contains filter, use the __in filter and pass in an iterable. This is the equivalent of SQL's IN keyword. More info on different field lookups in Django here.

class TagListAPIView(generics.ListAPIView):
    serializer_class = serializers.TagSerializer

    def get_queryset(self):
        search_words = self.request.query_params['search_with'].split()
        queryset = Tag.objects.filter(name__in=search_words)

        return queryset

It's worth keeping in mind that querysets in Django do not behave much at all like standard lists in Python. There is an & and | operator for combining querysets and it's worth reading about that here. That said, when you find yourself trying to invent a clunky workaround to manipulate a queryset, it's usually a good sign that it's time to dig into the docs for a better solution. That's been my experience anyway.

Adam Richard
  • 460
  • 4
  • 13
  • I returned different result from DB compared to my answer – Bigair Apr 03 '20 at 08:08
  • That's because the `in` filter will only return exact matches unlike `contains` which is the same as writing `WHERE your_field LIKE '%wordToSearch%'` in SQL. To be able to get this to work with just filters you might want to check out the regex/iregex filter. Though if you've got it working with your solution, maybe stick with that. – Adam Richard Apr 04 '20 at 19:22