qs1 and qs2 from the same Django model, what will be the count of combined_qs = qs1 | qs2 if qs1 has 3 items and qs2 has 4 items with 2 overlapping records?qs1 = Model.objects.filter(field__startswith='A') # 3 items qs2 = Model.objects.filter(field__endswith='Z') # 4 items combined_qs = qs1 | qs2 print(combined_qs.count())
The | operator combines two querysets and removes duplicates. Since 2 records overlap, total unique records are 3 + 4 - 2 = 5.
staff_qs = User.objects.filter(is_staff=True) verified_qs = User.objects.filter(email_verified=True) combined_qs = ???
The | operator combines two querysets with an OR condition, including unique records from both. The & operator is for intersection (AND).
| cause an error?qs1 = Author.objects.filter(active=True) qs2 = Book.objects.filter(published=True) combined_qs = qs1 | qs2
The | operator requires both querysets to be from the same model. Here, Author and Book are different models, so chaining raises a TypeError.
qs1 with 5 items and qs2 with 3 items (all in qs1), what is the count of result_qs = qs1.exclude(pk__in=qs2)?qs1 = Model.objects.filter(active=True) # 5 items qs2 = Model.objects.filter(active=True, status='inactive') # 3 items, all in qs1 result_qs = qs1.exclude(pk__in=qs2) print(result_qs.count())
The exclude removes the 3 items from qs1 that are in qs2, leaving 2 items.
| preferred over concatenating lists?| is better than converting querysets to lists and concatenating them?Using | chains querysets lazily, so the database query runs only when needed, improving performance. Converting to lists fetches all data immediately, which can be slow and memory-heavy.
