0

I have 2 querysets from 2 different models like this:

qs1=[[username1, lastname1, firstname1], [username2, lastname2, firstname2]........[username10, lastname10, firstname10]]
qs2=[[username1, email1], [username2, email2]...[username10, email10]]

I need to combine them to one and sorted by username. So it becomes like this:

qs=[[username1, lastname1,  firstname1, email1], [username2, lastname2,  firstname2, email2]...[username10, lastname10,  firstname10, email10]]

qs1 and qs2 are querysets with multiple entries.

I have code in view.py like this:

usernames = C.objects.values('username')
for username in usernames:
    try:
       qs1=A.objects.filter(username=username).values('username','lastname',' 'firstname')
       qs2=B.objects.filter(username=username).values('username','email')

qs = sorted(chain(qs1, qs2))
return qs

How do I combine qs1 and qs2 to qs?

2
  • Normally, django support Easy query like Model.Object.xxx. If you want to create some extra thing, i recomment you to use Raw query Commented Jan 25, 2018 at 8:57
  • will be more helpful if you post your model instead. Commented Jan 25, 2018 at 9:04

1 Answer 1

2

Use itertools

from itertools import chain
result_list = list(chain(qs1, qs2))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Chain works ok. However, why I am only getting last entry for qs? I tried to append or update qs, it did not work.
So qs = [username10, lastname10, firstname10, email10]. I need to get result of qs = [[username1, lastname1, firstname1, email1], [username2, lastname2, firstname2, email2]...[username10, lastname10, firstname10, email10]]

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.