【发布时间】:2021-12-16 01:54:38
【问题描述】:
假设我有一个这样的 Post 模型:
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
text_content = models.CharField()
@property
def comment_count(self):
return self.comments.count()
假设我需要获取 ID 为 3 的帖子的所有数据。我知道我可以通过 Post.objects.select_related('user').get(pk=3) 在一个查询中检索用户和帖子,这样我就可以保存查询。但是,有没有办法自动获取comment_count?
我知道我可以使用Post.objects.annotate(comment_count=Count('comments'))(这将需要我删除属性或更改注释的名称,因为会有AttributeError),但是是否可以让 ORM 自动执行该部分,因为属性是在模型中声明的?
虽然我可以只添加 .annotate,但当需要在多个位置获取多个属性和外键时,这会变得非常乏味。
【问题讨论】:
标签: django orm django-queryset