Skip to content

Instantly share code, notes, and snippets.

@soukiassianb
Last active February 19, 2023 10:00
Show Gist options
  • Save soukiassianb/7e835fe773b2d7c43375 to your computer and use it in GitHub Desktop.
Save soukiassianb/7e835fe773b2d7c43375 to your computer and use it in GitHub Desktop.
Use python set to compare django querysets
"""
First technique, use set
"""
# two querysets or lists
q1
>>> [<obj1>,<obj2>, <obj3>]
q2
>>> [<obj4>,<obj2>, <obj5>]
# compare querysets :
set(q1) == set(q2)
>>> False
# get objects present in both
set(q1).intersection(set(q2))
>>> <obj2>
# get objects of q1 not in q2
set(q1).difference(set(q2))
>>> <obj1> <obj3>
# vice versa
set(q2).difference(set(q1))
>>> <obj4> <obj5>
"""
Second technique, use exclude / filter
"""
@RomarioSoekhoe
Copy link

Where is the second technique?

@todrgor
Copy link

todrgor commented May 7, 2022

thank you maaan

@orhanna14
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment