2
class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    booked_at = models.DateTimeField(default=timezone.now)
    bought = models.BooleanField(default=False)

I would like to group tickets by booked day, and then again group each day's ticket list by ticket's user (admin / customer) i.e., user is_admin or not, finally to get list of ticket or ticket's id.

[
    {
        'day': datetime.datetime(2018, 5, 6, 0, 0, ...), 
        'booked_by_admin': [1, 2, 5],
        'booked_by_customer': [3, 4]
    }, 
    {
        'day': datetime.datetime(2018, 5, 7, 0, 0, ...), 
        'booked_by_admin': [11, 12, 16],
        'booked_by_customer': [10, 13, 14, 15]
    }
]

I could group tickets by day this way,

Ticket.objects.filter(bought=True).annotate(day=TruncDay('booked_at')).values('day').annotate(c=Count('id')).order_by()

But I cannot figure out how to again group it by admin user and non admin user to get list of ticket objects. Could you help me please.

Aamu
  • 3,431
  • 7
  • 39
  • 61
  • 1
    did u trie add `.order_by('user__is_admin')` at the end of your query? where *user__is_admin* - field of your related `user` model. – Chiefir May 07 '18 at 12:25
  • @Chiefir Ok, `.order_by('user__is_admin')` does help a bit by separating the results in to two. But there is no way to tell if its of admin or non admin. Also how can I return list of object or object's id. – Aamu May 07 '18 at 13:00
  • have a look at https://github.com/kako-nawao/django-group-by module, may be this is what u need. It looks like Django does not have that functionality at the moment what u need. – Chiefir May 07 '18 at 13:12
  • @Chiefir Yes, I was just looking into that. – Aamu May 07 '18 at 13:21

0 Answers0