Complex Query Question

1 view
Skip to first unread message

mystand

unread,
Nov 20, 2009, 6:03:22 PM11/20/09
to django...@googlegroups.com

Hi all,

I have a question about a complicated query I need to do. I have a model for
an event like this:

class Events(models.Model):
default_group = models.ForeignKey(Group, related_name='default_group',
null=True)
group = models.ManyToManyField(Group)
users = models.ManyToManyField(User)
title = models.CharField(max_length=255)
shortname = models.SlugField(max_length=25, unique=True)

plus some more fields that are not relevant to this question.

This is for a event registration site. The default group must be chosen from
the event creator's groups. group can be any group and users can be any
users.

I need to do a query that selects all Events that a logged in user can edit.
They can edit an event if they are in the default group, if they are in any
of the other groups, or they are one of the users added to the event.

I've read the docs and am still missing something. How can I do this query
as elegantly as possible?

Thanks,
A Django Newbie.
--
View this message in context: http://old.nabble.com/Complex-Query-Question-tp26451658p26451658.html
Sent from the django-users mailing list archive at Nabble.com.

Javier Guerra

unread,
Nov 20, 2009, 10:21:33 PM11/20/09
to django...@googlegroups.com, mystand
mystand wrote:
> I need to do a query that selects all Events that a logged in user can edit.
> They can edit an event if they are in the default group, if they are in any
> of the other groups, or they are one of the users added to the event.

first of all, it might be easier if you follow the database convention of naming your tables in singular. in this case, your events model should be called 'Event' and not 'Events'. that makes it more readable when you use singular in ForeignKey fields and plural in ManyToManyField's

in your case, the general strategy is to use Q() objects. the idea is to define each possibility separately and then join them all with the '|' operator. something like this (untested):

@login_required
def editable_groups(request):
user = request.user
evs_by_defgroup = Q(default_group__in=user.group_set)
evs_by_groups = Q(group__in=user.group_set)
evs_by_users = user.events_set

myevents = Events.objects.filter (evs_by_defgroup | evs_by_groups | evs_by_users)
return render_to_response ("template.html", {'myevents':myevents})


(i'm not sure about '|'ing the Q() objects with the queryset 'user.events_set', but i don't know how to express this as a Q() object)


--
Javier
Reply all
Reply to author
Forward
0 new messages