Reputation: 453
Disclaimer: I did not create this model. I know it's not a good one and it should be refactored. But I can't change it and I have to work with it. Also, sorry if I made any grammar mistake, english is not my first language.
I have this (simplified) model, where an Event has a group, and this group has many users.
class Event():
clients_group = models.ForeignKey("ClientsGroup")
class ClientsGroup():
group_name = models.CharField()
clients = models.ManyToManyField("Client")
class Client():
user = models.OneToOneField(User)
When a user logs in, I need to get a list of events that this user is related to.
I tried this:
list_of_events = Event.objects.filter(clients_group__clients__user__username=logged_in_user.username)
But I get an empty list.
Upvotes: 1
Views: 60
Reputation: 46
Your client field in the ClientsGroup model is incorrect. It should be
clients = models.ManyToManyField("Client")
not
clients = models.ManyToMany("Client")
When you fix that, I think it should work. Double check that your models do actually have objects in them and that they link to eachother.
If it still doesn't work after changing the field name, try splitting up your query to debug. For example you could the query into two seperate queries
target_client = Client.objects.get(user=logged_in_user)
list_of_events = Event.objects.filter(clients_group__clients=target_client)
From here you can figure out which queries are working and which aren't.
Upvotes: 2