Prometheus Prometheus - 9 months ago 31
Python Question

How to chain a queryset together in Django correctly

Using the example below, I'm trying to use a queryset and append/chain filters together. To my understanding last

should have just 1 instance, but it always had the original 10 in it.

Expected output of last
is 1:

# Set a default queryset.
def get_queryset(self, *args, **kwargs):
queryset = super(UserMixin, self).get_queryset(*args, **kwargs)
queryset.count() # 10 instacnes
queryset.count() # 10 instacnes excpeted 1

I can solve this problem I think by:

queryset = queryset.filter(id=1)

Is this the correct way or there a way to chain them correctly where I can add the queryset object around?


You never assign the filter to anything so it doesn't update it

 queryset = queryset.filter(id=1)

Yes this is the correct way because you are creating a new query, otherwise you need to call the count on the end of the previous filter call