Finding posts in certain categories which you haven't voted on (django-voting, django-categories)

StackOverflow https://stackoverflow.com/questions/14701802

  •  06-03-2022
  •  | 
  •  

Question

I have an app where Posts are split into various categories using the django-categories app, using hard-linking (ForeignKey to categories.Category).

I am also using the django-voting app to allow users to vote_up or vote_down certain posts.

Now I have a view where I require the latest posts from a list of Categories (the users category whitelist) which the user has NOT voted on and they are not his own posts. How do I go about getting these posts in the most efficient manner from the DB query load perspective.

Here is my Post model:

class Post(models.Model):
    published = models.DateTimeField(default=datetime.now)
    author = models.ForeignKey(User, blank=True, null=True,
                               verbose_name='author', 
                               related_name='author_post')
    caption = models.CharField(max_length="240")
    image = models.ImageField(upload_to='user_images')
    up_votes = models.PositiveIntegerField(default=0)
    down_votes = models.PositiveIntegerField(default=0)
    category = models.ForeignKey('categories.Category')

Should I use RAW DB queries to get posts in reverse chronological order where the current logged in user hasn't voted and they aren't his own posts.

Was it helpful?

Solution

Depends on your db. If it's PosgtreSQL, you will be fine with subquery.

voted_already = (Vote.objects.filter(user=…, 
                                     content_type=…)
                             .values_list('object_id', flat=True))
not_voted = (Post.objects.filter(category__in=…)
                         .exclude(author=…, 
                                  pk__in=voted_already)
                         .order_by('-published'))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top