How to perform grouping and ordering

22 views
Skip to first unread message

Aamu Padi

unread,
Apr 23, 2017, 1:58:10 PM4/23/17
to django...@googlegroups.com
I have a Ticket booking model

class Movie(models.Model):
   name = models.CharField(max_length=254, unique=True)

class Show(models.Model):
   day = models.ForeignKey(Day)
   time = models.TimeField(choices=CHOICE_TIME)
   movie = models.ForeignKey(Movie)

class MovieTicket(models.Model):
   show = models.ForeignKey(Show)
   user = models.ForeignKey(User)
   purchased_at = models.DateTimeField(default=timezone.now)

I would like to filter MovieTicket with its user field and group them according to its show field, and order them by the booked_at field. And respond back with json data using Django rest framework like this:

[
   {
       show: 4,
       movie: "Lion king",
       time: "07:00 pm",
       day: "23 Apr 2017",
       total_tickets = 2
   },
   {
       show: 7,
       movie: "Gone girl",
       time: "02:30 pm",
       day: "23 Apr 2017",
       total_tickets = 1
   }
]

I tried this way:

>>> MovieTicket.objects.filter(user=23).order_by('-booked_at').values('show').annotate(total_tickets=Count('show'))
<QuerySet [{'total_tickets': 1, 'show': 4}, {'total_tickets': 1, 'show': 4}, {'total_tickets': 1, 'show': 7}]>

As you can see its not grouping according to the show. Also how can I add other related fields (i.e., show__movie__name, show__day__date, show__time)?
Reply all
Reply to author
Forward
0 new messages