我正在使用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
对象?
[我发现使用lambda
从另一个SOF答案中的prefetch_related中获取max
值:https://stackoverflow.com/a/12609454/3719167
是否也可以使用lambda
来过滤查询集?
您是否尝试过过滤关系的属性?
user = User.objects.prefetch_related(
'relation'
).filter(
relation__status='active'
).get(pk=request.user.pk)