我正在使用Django 2.2
我有许多与模型反向相关的User
模型,我想从每个具有不同过滤器的模型中获取计数。
例如,我有一个Relations
模型
status = (
('Active', 'active')
('Inactive', 'inactive')
)
class Relation(models.Model):
user = models.ForeignKey(User, related_name='relation')
status = models.CharField(choices=status, default=ACTIVE)
现在我想为用户分别获取每个状态的计数和查询集。为此,我在模型中定义了模型User
方法
def get_relation():
return self.relation.all()
def get_active_relation(self):
return self.relation().filter(status='active')
def get_inactive_relation():
return self.relation().filter(status='inactive')
def get_active_count():
return self.get_active_relation().count()
def get_inactive_count():
return self.get_inactive_relaiton().count()
我有用户对象
user = User.objects.prefetch_related(
'relation'
).get(pk=request.user.pk)
现在,当我得到计数时,它会为此执行一个额外的查询
user.get_active_count()
如何过滤prefetch_related
对象?
我在另一个 SOF 答案中发现了一个用于从 prefetch_related 中lambda
获取值的方法: https ://stackoverflow.com/a/12609454/3719167max
是否也可以用来lambda
过滤查询集?