Django泛型关系问题
我在我的一个视图中提出过滤器时遇到问题。我正在创建一个包含博客条目、新闻文章和评论的网站。条目和文章与评论具有通用关系,因为评论可以标记它们中的任何一个。我想做的是根据比某个日期更新的评论的评分总和对条目/文章进行排序。
以下是简化的模型:
class Entry(models.Model):
name = models.CharField(max_length=50)
reviews = generic.GenericRelation(Review)
class Article(models.Model):
name = models.CharField(max_length=50)
reviews = generic.GenericRelation(Review)
class Review(models.Model):
rating = models.IntegerField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
target = generic.GenericForeignKey('content_type', 'object_id')
timestamp = models.DateTimeField(auto_now_add=True)
因此,考虑到我需要求和,我尝试使用注释和聚合,但遇到了两个问题。第一个是显然通用关系和注释不能很好地协同工作:https://code.djangoproject。 com/ticket/10461。第二个问题是,我认为不可能只对部分评论进行求和(在本例中,使用 timestamp__gte=datetime.now())。我这样做的方式不对吗?
我也考虑过以相反的方式这样做:
Review.filter(timestamp__gte=datetime.now(), target__in=something).aggregate(Sum('rating'))
但既然我试图根据此对评论进行排序,我是否不需要从 Review.something 开始,以便我可以使用 order_by ?
谢谢。
I'm having problems coming up with a filter in one of my views. I'm creating a site with blog entries, news articles, and reviews. The entries and articles have generic relations with the reviews, because the reviews can tag either of them. What I'm trying to do is to sort the entries/articles based on the sum of the ratings of reviews newer than a certain date.
Here are the simplified models:
class Entry(models.Model):
name = models.CharField(max_length=50)
reviews = generic.GenericRelation(Review)
class Article(models.Model):
name = models.CharField(max_length=50)
reviews = generic.GenericRelation(Review)
class Review(models.Model):
rating = models.IntegerField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
target = generic.GenericForeignKey('content_type', 'object_id')
timestamp = models.DateTimeField(auto_now_add=True)
So, given that I needed to find a sum, I tried using annotate and aggregate, but I ran into two problems. The first one is that apparently generic relations and annotations don't work nicely together: https://code.djangoproject.com/ticket/10461. The second issue is that I don't think it's possible to only sum part of the reviews (in this case, with timestamp__gte=datetime.now()). Am I doing this the wrong way?
I also thought about doing this the other way around:
Review.filter(timestamp__gte=datetime.now(), target__in=something).aggregate(Sum('rating'))
But since I'm trying to order the reviews based on this, don't I need to start with Review.something so I can use order_by?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我强烈建议使用 多表继承 而不是通用外键:
I would highly suggest using Multi-table inheritance instead of generic foreign keys:
经过一些研究,我发现解决我的问题的唯一方法是使用 QuerySets 的“额外”方法编写自定义 sql。
After doing some research, I found out that the only way to solve my problem was to write custom sql using the "extra" method of QuerySets.