[英]Excluding objects from Django queryset based on recency
I have a reddit-like Django app where users can post interesting urls (links) and then publicly comment under them. 我有一个类似reddit的Django应用,用户可以在其中发布有趣的url(链接),然后在其下公开评论。 The two data models to represent this are: 代表此的两个数据模型是:
class Link(models.Model):
description = models.TextField(validators=[MaxLengthValidator(500)])
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now_add=True)
class Publicreply(models.Model):
submitted_by = models.ForeignKey(User)
answer_to = models.ForeignKey(Link)
submitted_on = models.DateTimeField(auto_now_add=True)
description = models.TextField(validators=[MaxLengthValidator(250)])
How do I query for all Links
which have at least 1 or more publicreply
, and secondly where the latest publicreply
is not by self.request.user
? 如何查询所有Links
,其至少有1个或多个publicreply
,其次在最新publicreply
是不是 self.request.user
? I sense something like the following: 我感觉如下:
Link.objects.filter(publicreply__isnull=False).exclude(**something here**)
Please advise! 请指教! Performance is key too, hence the simpler the better! 性能也是关键,因此越简单越好!
For performance and simplicity you could cache both the number of replies and the latest reply: 为了提高性能和简化性,您可以缓存答复数和最新答复:
class Link(models.Model):
...
number_of_replies = models.PositiveIntegerField(default=0)
latest_reply = models.ForeignKey('myapp.Publicreply', related_name='+', blank=True, null=True, on_delete=models.SET_NULL)
When a reply is entered, update the corresponding link.number_of_replies
and link.latest_reply
. 输入回复后,更新相应的link.number_of_replies
和link.latest_reply
。
The query would then be: 该查询将是:
Link.objects.filter(number_of_replies__gte=1)\
.exclude(latest_reply__user=request.user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.