Reputation: 3
I am using an event log plugin which I am trying to filter a queryset from the Log model which doesn't seem too complicated, although I can't seem to get it to work.
My models (which are simplified for relevancy but important info there):
class User (model.Models)
standard User Registration data
class UserProfile(model.Models)
user = models.OneToOneField(User)
user_company = models.ForeignKey('Company')
class Company(models.Model)
name = models.CharField(max_length=50)
class Log(models.Model)
user = models.ForeignKey('User')
I am trying to filter all logs from the same company of the current user. I've been trying to use:
user_company = request.user.profile.user_company
log = Log.objects.filter(user=user_company)
but no luck. What am I missing?
Upvotes: 0
Views: 120
Reputation: 3755
Instead of:
log = Log.objects.filter(user=user_company)
Try:
log = Log.objects.filter(user__userprofile__user_company=user_company)
You are starting with the Log object, so you have to work backwards with the relationships you have. Log is tied to User, which is related to UserProfile, which contains user_company. So if you're filtering a log queryset, the lookup goes from user - userprofile - user_company. The double underscores between each tell the ORM to look for a related field.
This should give you all logs where the associated user is a member of your defined user_company, which you're getting through the request.
I am no database wizard, but this seems like a pretty intense lookup to me. Maybe you could cut out a step and reduce the load by relating the logs to a UserProfile instead of a User?
Upvotes: 2
Reputation: 6065
You should filter by user, not by user company.
Try this:
log = Log.objects.filter(user=request.user)
Upvotes: 0