When user login i want user to only see the post of friends with, I have a separate model for friends and a separate for post how do i filter post by users friends ?
Here is my view
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 model
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)
CodePudding user response:
Try this
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)
UPDATE
show current user posts and current user's friends posts.
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)