Complex request with Django (messages from all friends)

I am new to Python and Django, so please be patient with me.

I have the following models:

class User(models.Model): name = models.CharField(max_length = 50) ... class Post(models.Model): userBy = models.ForeignKey(User, related_name='post_user') userWall = models.ForeignKey(User, related_name='receive_user') timestamp = models.DateTimeField() post = models.TextField() class Friend(models.Model): user1 = models.ForeignKey(User, related_name='request_user') user2 = models.ForeignKey(User, related_name='accept_user') isApproved = models.BooleanField() class Meta: unique_together = (('user1', 'user2'), ) 

I know that this may not be the best / easiest way to handle it with Django, but I recognized it that way and I want to save it that way.

Now, all I want to do is get all the mail from one person and friends . Now the question is how to do this with Django filters?

I think in SQL it will look something like this:

 SELECT p.* FORM Post p, Friend f WHERE p.userBy=THEUSER OR ( (f.user1=THEUSER AND f.user2=p.userBy) OR (f.user2=THEUSER AND f.user1=p.userBy) ) 

Without a guarantee of correctness, just to give an idea of ​​the result I'm looking for.

+6
source share
2 answers
 from django.db.models import Q Post.objects.filter( \ Q(userBy=some_user) | \ Q(userBy__accept_user__user1=some_user) | \ Q(userBy__request_user__user2=some_user)).distinct() 

UPDATE

Sorry, that was my mistake. I did not pay attention to your related_name values. See updated code above. Using only userBy__accept_user or userBy__request_user will not work, because it will be a link to Friend , which you cannot compare with User . Here we do feedback with Friend , and then when we are there, we see if the other user in the friend’s request is the corresponding user.

It also illustrates the importance of adequately describing feedback relationships. Many people make the same mistake you made here and call related_name after the model in which they are created by FK ( User ), when in fact, when we talk about the opposite direction of FK, we are now talking about Friend . It’s just that your sibling names will make sense somehow like: friend_requests and accepted_friends .

+8
source
 (with User u) friends_u1 = Friend.objects.filter(user1 = u).getlist('user2_id', flat=True) friends_u2 = Friend.objects.filter(user2 = u).getlist('user1_id', flat=True) friends_and_user = friends_u1+friends_u2+u.id Post.objects.filter(userBy__id__in = friends_and_user) 
0
source

Source: https://habr.com/ru/post/927603/


All Articles