0

I want to merge these two QuerySets. HotkeyAndPrefix do not have entries for every Collection in all_collections. This means len(all_collections) >= len(all_collections_hotkeys_and_prefixes). How can i merge these two QuerySets? If there is no entrie found for a Collection in HotkeyAndPrefix I want hotkey = None, prefix=None. Can I achieve this in one query?

models.py:

class Collection(models.Model):
    creator = models.ForeignKey(User, blank=True, null=True)
    ...

class HotkeyAndPrefix(models.Model):
    user = models.ForeignKey(User, null=True)
    assigned_collection = models.ForeignKey(Collection, null=True)
    hotkey = models.CharField(max_length=1, blank=True, null=True)
    prefix = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        unique_together = ('user', 'assigned_collection')

view.py

admin = User.objects.filter(username='admin')[0]
all_collections = Collection.objects.filter(creator=admin)
current_user = request.user
all_collections_hotkeys_and_prefixes = HotkeyAndPrefix.objects.filter(assigned_collection__in=all_collections, user=current_user)
5
  • what should be the value of user for the Collectionentries not in HotkeyAndPrefix ? Commented Jun 30, 2017 at 9:25
  • It is the value from the person(admin) who created the collection. admin = User.objects.filter(username='admin')[0] Commented Jun 30, 2017 at 9:30
  • How do you plan to merge two queryset of different types of objects? And what new information would that merge give? Commented Jun 30, 2017 at 9:36
  • I want to output all_collections in a table and if the current user has defined a hotkey/prefix for a collection I want to ouput it in the same table row. Commented Jun 30, 2017 at 9:40
  • I think for this what you can do is ouput two set one of collection for which a user has hotkey/prefix and another for which the user doesn't. Commented Jun 30, 2017 at 10:00

1 Answer 1

2

You need to use exclude() query. You can take the list of values which are in the HotkeyAndPrefix.objects.filter(assigned_collection__in=all_collections, user=current_user) queryset

using

all_collections_hotkeys_and_prefixes_values = all_collections_hotkeys_and_prefixes.values_list('assigned_collection',flat=True)

and you can filter out the value, not in the all_collections_hotkeys_and_prefixes_values with one more query

all_collections_hotkeys_and_prefixes_excluded = all_collections.exclude(pk__in=all_collections_hotkeys_and_prefixes_values)

now you have two querysets, one of collection for which a user has hotkey/prefix and another for which the user doesn't

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

Comments

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.