views:

24

answers:

1

I'm trying to get a query from a specific model. I'm having trouble getting it to filter the data correctly.

I've already fixed one bug where it was returning other users data but now its returning duplicates of one row of data in the model.

events = Event.objects.filter(club=user.get_profile().main_club) | Event.objects.filter(invclub=user.get_profile().main_club) | Event.objects.filter(invited=user)

That is the query I'm trying to execute.

The result that I am aiming for, is to have all events that the user has either manually been invited to (invited) their club has been invited (invclub) or their club is the host club (club)

I am probably approaching this in the wrong direction and there may very well be an easier way of doing this. Any help is greatly appreciated.

EDIT: comms.models

class Event(models.Model):
     title = models.CharField(max_length='255')
     club = models.ForeignKey(Club, verbose_name="Host Club")
     invclub = models.ManyToManyField(Club, verbose_name="Invited Clubs", related_name="Invited Clubs", blank=True)
     l_desc = models.CharField(max_length='255', verbose_name="Location Description")
     l_long = models.CharField(max_length='255', verbose_name="Longitude", blank=True)
     l_lat = models.CharField(max_length='255', verbose_name="Latitude", blank=True)
     edate = models.DateTimeField(default=datetime.now, verbose_name="Event Date", blank=True)
     length = models.CharField(max_length='255', verbose_name="Event Length", blank=True)
     invited = models.ManyToManyField(User, related_name="Invited Users", blank=True)
     attending = models.ManyToManyField(User, related_name="Attending Users", blank=True)
     declined = models.ManyToManyField(User, related_name="Declined Users", blank=True)
     description = models.TextField(blank=True)

Fixed:

Final solution uses the Q() Objects as suggested below, whilst appending the .distinct() function to ensure no duplicates are returned.

+1  A: 

What you are doing is taking three independent queries and OR-ing them together. I'm surprised that works at all.

Instead, what you need is one query with three criteria, which are OR-ed together. You achieve this in Django via Q() objects:

from django.db.models import Q
main_club = user.get_profile().main_club
events = Event.objects.filter(Q(club=umain_club) | Q(invclub=main_club) | Q(invited=user))
Daniel Roseman
This is certainly a more productive way to tackle this, however it doesn't resolve the duplications I'm experiencing.
Neil Hickman
Can't you just append `.distinct()` to get rid of the dupes?
meder
That works thanks meder
Neil Hickman
Daniel thanks for the Q tip, i've never used it before. I'll implement this a lot more too. I've added your answer as the final answer to my post too.
Neil Hickman