1

I have the following model:

class TimeStamp():
    mydate = models.DateTime()
    value = models.Integer()
    cat = models.CharField()

The data table would look something like this:

mydate   | value  | cat
=======================
1st Jan  | 10     | A
2nd Jan  | 10     | A
3rd Jan  | 10     | A
4th Jan  | 5      | A
1st Jan  | 5      | B
2nd Jan  | 20     | B
3rd Jan  | 15     | B
4th Jan  | 30     | B

output table would look like, so we join by matching dates, then order by value for A then by value for B. Note the table below is the expected output, notice the order of the dates and ordering of value_A and value_B

mydate   | value_A  | value_B
==============================
4th Jan  | 5        | 30
1st Jan  | 10       | 5
3rd Jan  | 10       | 15
2nd Jan  | 10       | 20

I can obtain 2 querysets:

qs_a = TimeStamp.objects.filter(cat='A')
qs_b = TimeStamp.objects.filter(cat='B')

I'm not sure how to then join these 2 together. Note that the | will merge the 2 sets which is not what I'm after... I would like to join these 2 querysets then order by A then B, so that the list of dates is in order of the values where Cat=A then values where Cat=B.

Lingster
  • 977
  • 10
  • 21
  • 1
    Does this answer your question? [How do I do an OR filter in a Django query?](https://stackoverflow.com/questions/739776/how-do-i-do-an-or-filter-in-a-django-query) – Klaus D. Jan 14 '20 at 12:41
  • no, the OR filter does not allow me to join the 2 querysets then order by the value for cat=B then cat=A – Lingster Jan 14 '20 at 12:43

1 Answers1

0

You can use itertools chain to do this.

from itertools import chain
qs_chain = chain(qs_a, qs_b)

Does this answer your question?

Siddharth Prajosh
  • 1,013
  • 2
  • 9
  • 16
  • note quite, this will join the 2 qerysets together, but I need to sort by the values where cat=A then cat=B – Lingster Jan 14 '20 at 12:49
  • You mean you want a query_set with cat='A' or 'B' and sort it by some value? Is this what you're looking for? `TimeStamp.objects.filter(cat__in=['A', 'B']]).order_by('value'`) – Siddharth Prajosh Jan 14 '20 at 13:47
  • yes the sort should firstly sort by the "values" where cat='A' then sort the values where cat='B'. Please see the example table with the 3 columns in my question – Lingster Jan 14 '20 at 15:15
  • When you run a query, you get an image of the table which satisfies your query. I don't think you can add both of them. But I think you can get values of those query and generate a dict which might satisfy your requirement. `final = {'4 Jan': {'val_A': X, 'val_B':Y}}` Will that be useful? – Siddharth Prajosh Jan 15 '20 at 04:41