仅向用户朋友显示 post

Display post to only user friends

当用户登录时,我希望用户只能看到 post 的朋友,我有一个单独的朋友模型和一个单独的 post 我如何过滤 post用户好友 ?

这是我的看法

def post_list(request):
    
    for user in Post.objects.all():
        if request.user.is_authenticated:
            friend_list = FriendList.objects.get(user=request.user )
            friends = friend_list.friends.all()
            context['friends'] = friends
 
  
    context['posts'] = Post.objects.prefetch_related('comments').filter(username=friends).order_by('-date_posted')
  
    return render(request,'feed/feed.html',context)    


Post 型号

class Post(models.Model):
    username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    description = models.TextField(max_length=500, blank=True)
    date_posted = models.DateTimeField(auto_now_add=True)
    video = models.FileField(upload_to="videos",blank=True,null=True)
    tags = models.CharField(max_length=100, blank=True)
    views = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="view")
    shared_body = models.TextField(blank=True, null=True)
    shared_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='+')
    shared_on = models.DateTimeField(blank=True, null=True)

试试这个

def post_list(request):
    
    context = {}
    if request.user.is_authenticated:
        friend_list = FriendList.objects.get(user=request.user )
        friends = friend_list.friends.all()
        context['friends'] = friends
        context['posts'] = Post.objects.filter(username__in=friends).order_by('-date_posted')
    return render(request,'feed/feed.html',context)

更新
显示当前用户的帖子和当前用户的好友帖子。

def post_list(request):
    
    context = {}
    if request.user.is_authenticated:
        friend_list = FriendList.objects.get(user=request.user )
        friends = friend_list.friends.all()
        context['friends'] = friends
        context['posts'] = Post.objects.filter(username__in=list(friends) + [request.user,]).order_by('-date_posted')
    return render(request,'feed/feed.html',context)