Reputation: 165182
Consider a Django model that forms a connection between two other model instances:
class User(models.Model):
pass
class Meeting(models.Model):
user_a = models.ForeignKey(User, related_name='a_meetings')
user_b = models.ForeignKey(User, related_name='b_meetings')
Now suppose you want to define a function that returns all of a User
s meetings, regardless of if he is side a
or b
. The naive implementation would be:
class User(models.Model):
@property
def meetings(self):
return list(self.a_meetings.all()) + list(self.b_meetings.all())
What's the 'right' way to have this function return the matching QuerySet
instead of a list? Bonus points for an elegant solution that doesn't use an ugly Q
query ;)
Upvotes: 1
Views: 17
Reputation: 599470
I think Qs are inevitable here.
The main principle with these things is always to start from the model you actually want to get: so since you want meetings, start there.
return Meeting.objects.filter(Q(user_a=self) | Q(user_b=self))
Upvotes: 2