1

I come across this syntax on stackoverflow

from itertools import chain 
result_list = list(chain(page_list, article_list, post_list))

I need to concatenate a bunch of QuerySets with something like this:

    prjExpList = list(chain(lvl for lvl in prjlvl))
    prjEnvList = list(chain(env for env in prjEnv))

This gives me an error of

AttributeError: 'QuerySet' object has no attribute '_meta'

My goal is to concatenate a bunch of QuerySets that's stored inside a list prjlvl and prjEnv How do I do that?

2
  • Can you give us the full stack trace? Commented Jul 7, 2017 at 19:27
  • Try list(chain(prjlvl, prjEnv)) Commented Jul 7, 2017 at 19:42

2 Answers 2

2

Are the QuerySets of the same model? You can just do

combined_queryset = queryset_1 | queryset_2 | queryset_3

To chain them together into one QuerySet. This means you can still do things with the QuerySet in the ORM, which is a big help.

Sign up to request clarification or add additional context in comments.

Comments

-1

Try:

prjExpList = list(chain.from_iterable(prjlvl))

Note that itertools.chain() takes a *args list of iterables, and that you can get the same unpacking behavior from the chain.from_iterable() class method.

See: https://docs.python.org/2/library/itertools.html#itertools.chain

3 Comments

This is an overkill . Just using list(queryset) would work fine
My understanding is that prjlvl is a list of querysets.
prjlvl is indeed a list of querysets. This solution works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.