Django - filter after a slice / filter on a query where the results were limited

There is a problem with understanding why I cannot filter after the request fragment and what is happening.

stuff = stuff.objects.all()
stuff.count()

= 7

If i go then

extra_stuff = stuff.filter(stuff_flag=id)
extra_stuff.count()

= 6. Everything is fine, and I have a new request in extrastuff without any problems

stuff = stuff.objects.all()[:3]
extra_stuff = stuff.filter(stuff_flag=id)

I get the error message "Unable to filter the request after the slice has been done."

How can I further filter the query, where I limited the number of results?

+4
source share
3 answers

You cannot use filter()after you cut the request. The error is pretty obvious.

Cannot filter a query once a slice has been taken.

You can make a filter in Python

stuff = stuff.objects.all()[:3]
extra_stuff = [s for s in stuff if s.stuff_flag=='flag']

To get the number or elements in extra_stuff just use len()

extra_stuff_count = len(extra_stuff)

Python , stuff , . , , , .

extra_stuff = Stuff.objects.filter(id__in=stuff, stuff_flag='flag')
+5

Django , . filter .

, Django:

extra_stuff = [s for s in stuff if s.stuff_flag==id]

, .

+6

2 .


total_stuff = StuffClass.objects.count()
extra_stuff = StuffClass.filter(stuff_flag=id)[:3]
extra_stuff_count = len(StuffClass.filter(stuff_flag=id))

, extra_stuff_count - , 3 300. ( ).

-2

Source: https://habr.com/ru/post/1619877/


All Articles