Anshul Gupta
Anshul Gupta

Reputation: 331

How to 'add' QuerySet in Django?

I have written the below code.

for number in numbers:
    booking_list = Booking.objects.filter(rooms=number)

Here, numbers is a list of numbers.

The problem with this code is that booking_list will only contain the QuerySet of the last number as the previous QuerySets will be overwritten but I want booking_list to contain all the QuerySets. Moreover, I want the QuerySets to be unique. In other words I want a union of the QuerySets.

The reason as to why the QuerySet may have repeated vaues is because rooms is a list of numbers.

Upvotes: 1

Views: 77

Answers (1)

Sunderam Dubey
Sunderam Dubey

Reputation: 8837

You can use __in lookup with distinct() so:

booking_list = Booking.objects.filter(rooms__in=[i for i in numbers]).distinct("rooms")

Upvotes: 1

Related Questions