RZAMarefat
RZAMarefat

Reputation: 143

How to filter Posts Query in order to just see the posts of friends and Myself in Django

Guys I have built up a friendship system in my social media and it works properly. The last step is to restrict each user to see the posts from his or her own and friends. The following shows everything which I have guessed would be important.

The view for the posts:

class PostListView(LoginRequiredMixin,ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    

    def get_queryset(self):
        friends = User.objects.get(id=self.request.user.id).profile.friends.all()
        posts = Post.objects.filter(author = self.request.user)

        return posts

    def get_friends(self):
        friends = User.objects.filter(profile.friends).all()
        return friends

the Post model:

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    content= models.TextField()
    image = models.ImageField(blank=True, null=True, upload_to='post_pics')
    likes = models.ManyToManyField(User, related_name='blog_post')
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        super().save()

        if self.image:
            img = Image.open(self.image.path)
            if img.height > 900 and img.width > 900:
                output_size = (900,900)
                img.thumbnail(output_size)
                img.save(self.image.path)
        
    def get_absolute_url(self):
        return reverse('post_detail', kwargs={'pk':self.pk})

    def get_number_of_likes(self):
        return self.likes.count()

    

The profile model which is is created via signals whenever a new user registers:

class Profile(models.Model):
    love_status_choices = [
        ('-', '------'),
        ('married', 'Married'),
        ('single', 'Single'),
        ('inrel', 'In Releationship')
    ]
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    image = models.ImageField(default='default.png', upload_to='profile_pics')
    bio = models.TextField(blank=True, null=True)
    expertise = models.CharField(max_length=100, blank=True, null=True)
    age = models .IntegerField(blank=True, null=True)
    love_status = models.TextField(choices=love_status_choices, default="-", blank=True, null=True)
    friends = models.ManyToManyField(User,blank=True, related_name='friends_list')


    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 and img.width > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)

Basically I want to filter my Post query in PostListView in order to get the posts from friends and the user him/herself

I think this much of my code is enough to answer but if anything else is needed please tell me. Thank you in advance.

Upvotes: 0

Views: 179

Answers (1)

Arjun Shahi
Arjun Shahi

Reputation: 7330

You can try like this.

def get_queryset(self):
    friends = self.request.user.profile.friends_list.all()
    your_posts = Post.objects.filter(author=self.request.user)
    friends_posts = Post.objects.filter(author__in=friends)
    all_posts = your_posts | friends_posts
    return all_posts
    

Upvotes: 1

Related Questions