我有一个应用程序,使用django-categories
应用程序使用硬链接(ForeignKey到categories.Category
)将帖子分成不同的类别。
我也在使用django-voting
应用,允许用户对某些帖子进行vote_up或vote_down。
现在我有一个视图,我需要用户未投票的Categories
(用户类别白名单)列表中的最新帖子,而且他们不是自己的帖子。如何从数据库查询加载角度以最有效的方式获取这些帖子。
这是我的帖子模型:
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')
我是否应该使用RAW数据库查询以反向时间顺序获取帖子,其中当前登录的用户尚未投票且他们不是自己的帖子。
答案 0 :(得分:1)
取决于您的数据库。如果它是PosgtreSQL
,你可以使用子查询。
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'))