0

I'm having trouble figuring out how to filter a queryset appropriately for the following scenario.

I have an event with many participants. Both models are imported from a foreign data source, so I want to keep a permanent copy of their data:

class Event(models.Model):
    address = etc...

class Participant(models.Model):
    event = models.ForeignKey('Event')
    user_profile = models.ForeignKey('people.UserProfile', blank=True, null=True)
    name = etc...

When the foreign data source receives a new event, it sends me a copy, which I fill into these models. The import script uses the Participant's name field to try and find them in its existing list of people, and if so, it establishes the foreign key.

I have the currently logged in UserProfile on hand, and Event.objects.all. I want to filter the Events by the currently logged in user. What should the arguments to .filter() be to achieve this?

4
  • 1
    Can you clarify exactly what you mean by "filter out"? It's one of those phrases that can mean its own reverse. Do you mean you only want the events that don't belong to the current user, or you only want the events that do belong to the current user? Commented Jun 18, 2012 at 18:29
  • I want something like Event.filter(participants__user_profile=UserProfile.objects.get(user=get_current_user()))... Commented Jun 18, 2012 at 18:31
  • So those that do belong to the current user. Commented Jun 18, 2012 at 18:31
  • With Event.objects, of course. Commented Jun 18, 2012 at 18:37

2 Answers 2

1

First, you have a ForeignKey to auth.User named user_profile. That's quite confusing.

Second, if you want all events NOT related to current user, you want:

Event.objects.exclude(participant__user_profile=request.user)
Sign up to request clarification or add additional context in comments.

3 Comments

In this case, you can change the code use request.user.get_profile() instead. Don't pull the UserProfile in the queryset because chances are Django will have a cached copy already, so you skip one DB trip.
I believe this is wrong. It throws FieldError: Cannot resolve keyword 'participant_set' into field. Participant_set is just a RelatedManager on the model Event, not an attribute. But django does provide you with a sudo-attribute to filter on, participant, hence my answer below.
You're correct Chris, it's my typo now. The field will be just the name of the related model.
0

It appears that it works without the plural.

Event.objects.filter(participant__user_profile=UserProfile.objects.get(user=get_current‌​_user()))

1 Comment

This will give you all events those belong to currently logged in user but your question statement is opposite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.