Sunday, April 23, 2017

How to perform grouping and ordering

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)?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAHSNPWs_6jmDsMGnJ79O21bhkKhpwq0NLjgGtLUK2njdC%2BfYHw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment