I found two ways to implement a symmetric friendship system (you are my friend, so I am also your friend) in Django:
As stated in the docs:
class UserProfile(models.Model): friends = models.ManyToManyField(User, related_name='friends')
Now I would like to get all the "friendly" user and user models with one similar select_related-query (this should be a reverse combined search):
profiles = UserProfile.objects.filter(user__in=request.user.get_profile().friends.all()).select_related()
I request userprofile because this way I can use select_related () and all related objects are cached.
On the other hand, I can determine that my model refers to the friends field as "I", for example:
class UserProfile(models.Model): friends = models.ManyToManyField('self')
Now my search related to select_related looks like this:
profiles = this_user.get_profile().friends.all().select_related()
I always need both a user object and a profile associated with it. The second approach is much simpler with respect to reverse lookups using select_related (), but almost the same. However, using self as a field link, Django handles symmetrical friendships for me. This way, I do not need to manually create two friendship records in the database. Django does it for me. The symmetric parameter, however, only works with self fields.
What is the best solution? I can do nothing about it. Any ideas appreciated - thanks!
source share