我正试图从以下用户(例如Facebook,Instagram和Twitter)获得提要。我写了一个视图来显示跟随者的提要。
class Following(View):
def get(self, request):
user = request.user
posts = models.Post.objects.filter(creator__in=user.following.all()).order_by('created_date')[:5]
我很担心是否可能由于user.following.all()部分而导致性能问题。我不知道为什么
filter(creator=user.following)
不起作用。
以下是自引用的ManyToManyField。
followers = models.ManyToManyField("self", blank=True)
following = models.ManyToManyField("self", blank=True)
有更好的解决方案吗?
在计算许多ManyToManyFields方面还有另一个问题。
class Popular(View):
def get(self, request):
user = request.user
posts = models.Post.objects.annotate(number_of_likes=Count('likes'), number_of_comments=Count('comments')).filter(Q(channels__users=user) & (Q(number_of_likes__gte=5) | Q(number_of_comments__gte=5))).order_by('created_date')[:5]
之所以这么久,是因为Likes__count和comments__count无效。我在互联网上发现唯一可行的情况是使用anateate()。有更好的解决方案吗?我想过滤掉具有用户订阅渠道的帖子,在其中,我只想显示喜欢的次数或评论的数量超出一定范围。为什么这不起作用?
models.Post.objects.filter(Q(channels__users=user) & (Q(likes__count__gte=5) | Q(comments__count__gte=5))).order_by('created_date')[:5]
class Comment(news_models.TimeStampedModel):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
class Like(news_models.TimeStampedModel):
comment = models.ForeignKey(Comment, null=True, on_delete=models.CASCADE, related_name='likes')
class Channel(models.Model):
name = models.CharField(max_length=100, blank=False, unique=True)
users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='channels')
posts = models.ManyToManyField(Post, related_name='channels')