Is it possible to combine multiple values_list() in Django?

django join two models
merging queryset' classes must involve the same values in each case
django union two querysets
django filter in list
django values_list
django iterate over queryset
django queryset get field value
django append to queryset

As the title suggests, I have multiple sets of queries that each return a values list. I then use the values list to filter another queryset. At the moment I can only do this second step one queryset at a time. Is it possible to combine my initial values lists into one super long list? I'm trying to create an activity/news feed like feature.

cookie_ids = Cookie.objects.filter(board__pk=self.kwargs['pk']).values_list('id',

sugar_ids = Sugar.objects.filter(board__pk=self.kwargs['pk']).values_list('id',

context['cookie_actions'] = Action.objects.filter(target_id__in=cookie_ids)
context['sugar_actions'] = Action.objects.filter(target_id__in=sugar_ids)

Edit: I think this is the only model that might matter
class Action(models.Model):
    user = models.ForeignKey(User,
    verb = models.CharField(max_length=255)

    target_ct = models.ForeignKey(ContentType,
    target_id = models.PositiveIntegerField(null=True,
    target = GenericForeignKey('target_ct', 'target_id')
    created = models.DateTimeField(auto_now_add=True,

    class Meta:
        ordering = ('-created',)

You can use chain to combine your querysets

from itertools import chain
cookie_ids = Cookie.objects.filter(board__pk=self.kwargs['pk']).values_list('id',flat=True)

sugar_ids = Sugar.objects.filter(board__pk=self.kwargs['pk']).values_list('id',Ôflat=True)

ids_list = chain(cookie_ids, sugar_ids)
context['total_actions'] = Action.objects.filter(target_id__in=ids_list)

Django Tips #5 How to Merge QuerySets, At this point we have two different querysets, one containing all the stories from a medium and other containing all the The querysets can be merged like in the example below, using the | operator: And you still can perform queryset operations: recent_stories = stories.distinct().order_by('-date')[:10]. Add a similar warning under the .values_list() reference. Or modify the above warning. The modification I am suggesting would be in the last line: This will be especially pronounced if you include multiple such fields in your values() or values_list() query, in which case all possible combinations (including None) will be returned.

I think this is what you want



ids_list = list(cookie_ids) + list(sugar_ids)
context['total_actions'] = Action.objects.filter(target_id__in=ids_list)

5. How to do union of two querysets from same or different models , You can do a union on two models as long as they have same fields or same subset of fields. Since Hero and Villain both have the name and gender , we can use values_list to limit the selected fields then do a union. stories = django_stories | vitor_stories # merge querysets. And you still can perform queryset operations: recent_stories = stories. distinct (). order_by ('-date')[: 10] It’s important to note that the merge/combine operator | only works on querysets from the same model and before the slicing it.

QuerySet API reference | Django documentation, repr(). A QuerySet is evaluated when you call repr() on it. This is for convenience However, it is safe (and fully supported) to pickle and unpickle the attribute's of the field in the new model, and so on for as many models as you want to join. CRUD multiple records in Django models. In this section you'll learn how to work with multiple records in Django models. Although the process is just as easy as working with single model records, working with multiple records can require multiple database calls, as well as caching techniques and bulk operations, all of which need to be taken into account to minimize execution times.

#26641 (Unable to concatenate 2 fields when filtering) – Django, Unable to concatenate 2 fields when filtering You should be able to use the Concat function for this purpose: from django.db.models import Value from� Only in Django 1.6 and 1.7, due to Django bug #9619, passing a MultiSelectField to values() or values_list() will return the database representation of the field (a string of comma-separated values). The workaround is to manually call .split(',') on the result.

Combine Two Querysets in Django (With Different Models), values_list(field) - This is similar to values() except that instead of returning dictionaries, 2 common ways to call this function - examples: Get the results of a query as tuples. Each tuple contains the value from the respective field passed into the values_list() call — so the first item is the first field, etc. Join the tribe. Django doesn’t support that mode of access (slicing from the end), because it’s not possible to do it efficiently in SQL. Also, note that reverse() should generally only be called on a QuerySet which has a defined ordering (e.g., when querying against a model which defines a default ordering, or when using order_by() ).

values_list - django - Python documentation, Combining Filters. One final tip is that it is possible to combine multiple field lookups by chaining together filter() or exclude()� Just as with Python’s subclassing, it’s possible for a Django model to inherit from multiple parent models. Keep in mind that normal Python name resolution rules apply. The first base class that a particular name (e.g. Meta ) appears in will be the one that is used; for example, this means that if multiple parents contain a Meta class, only

  • please show your models.
  • your using content type, filtering by target_id only will conflict.
  • @naqibhakimi now that you mentioned it, I just went back and checked what I thought was working already and (using only cookie_ids) and there's data showing up form other boards. SO when you say conflicts, what do you mean? Any idea on why this is happening?
  • That looks so easy it's sinful. I'll try it out then update
  • Also a useful solution. I actually just tried and used this for something similar. Thanks mate
  • I am glad that it helped. Cheers.