0

I am new to python/django so please bear with me.

I have QuerySet qrySet.values_list('group_id', 'date', 'time', 'mobile')

with that I get list like this

[1, datetime.date(2018, 9, 8), datetime.time(18, 39), 'phone1']
[2, datetime.date(2018, 9, 12), datetime.time(4, 0), 'phone1']
[2, datetime.date(2018, 9, 19), datetime.time(4, 0), 'phone2']
[2, datetime.date(2018, 9, 19), datetime.time(4, 0), 'phone4']
[9, datetime.date(2018, 9, 10), datetime.time(4, 35), 'phone3']
[9, datetime.date(2018, 9, 17), datetime.time(4, 35), 'phone3']
[9, datetime.date(2018, 9, 18), datetime.time(4, 35), 'phone3']

I am trying to put all phone numbers together that have same group_id, date and time, something like this [[group_id, date, time, [phone1, phone2, phone9]]

Is there anything built-in in Django or python for this kind of thing?

I tried some SO solutions using lambda but they group based on one value while I have three.

Thank you

2
  • Is this a sorting question or are you trying to have just one record per phone? Commented Sep 5, 2018 at 10:46
  • What's your database? Postgres supports an ArrayAgg: stackoverflow.com/questions/43203014/… Otherwise you'll have to end up doing some post processing to get a phone number list. Commented Sep 5, 2018 at 10:57

1 Answer 1

0

You could try itertools.groupby:

from itertools import groupby

[list(key) + [[g[3] for g in group]] 
    for key, group in groupby(
        qrySet.values_list('group_id', 'date', 'time', 'mobile'), 
        key=lambda x: (x[0], x[1], x[2]))]

With your example data, that gives:

[[1, datetime.date(2018, 9, 8), datetime.time(18, 39), ['phone1']],
 [2, datetime.date(2018, 9, 12), datetime.time(4, 0), ['phone1']],
 [2, datetime.date(2018, 9, 19), datetime.time(4, 0), ['phone2', 'phone4']],
 [9, datetime.date(2018, 9, 10), datetime.time(4, 35), ['phone3']],
 [9, datetime.date(2018, 9, 17), datetime.time(4, 35), ['phone3']],
 [9, datetime.date(2018, 9, 18), datetime.time(4, 35), ['phone3']]]
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.