Hey All,

I have the following models:

class Company:
>     name = models.CharField(max_length=200)
>
 

> class Event:
>     title = models.CharField(max_length=200)
>     company = models.ForeignKey(Company)
>
 

> class EventRegistration:
>     attended = models.BooleanField(default=False)
>     event = models.ForeignKey(Event)


Each Company can have several Events attached to it, and when people 
register for an Event, an EventRegistration is created. If they actually 
attend the Event, then that EventRegistration for that particular user is 
set to "attended=True".

I'm currently generating reports, and what I need is essentially a way to 
have the Company see all of their Events, and sort by the number of 
attendees (EventRegistrations with "attended=True"). I have this SQL that 
accomplishes what I need:

SELECT e.title FROM example_event e LEFT JOIN (SELECT event_id, COUNT(*) 
> attendees FROM example_eventregistration WHERE attended=1 GROUP BY 
> event_id) r ON (e.id=r.event_id) ORDER BY r.attendees DESC;


That gives me exactly what I want, which is a sorted list of Events. Well, 
I really need more than just "e.title"; I actually need the whole object, 
but this gives an idea of what I'm looking for. Is there any way to do this 
in the Django ORM? I would need something like:

events.annotate(attendees=Count('eventregistration__attended=True')).order_by('attendees')


... I'm well aware that won't work, because you can't have conditions 
within the string argument of Count(), but again, this is the idea of what 
I want. Does anyone know the right way to do this? The "events" variable 
needs to always have ALL of the Events from the Company, regardless of 
whether anyone has attended that Event or not. The only difference is how 
those Events are sorted (so events.filter(eventregistration__attended=True)will 
not give me what I want, because that returns only a subset of Events).

Thanks in advance!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/JOKVPCx00zYJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to