与预取相关的查询集的Django过滤器

问题描述 投票:0回答:1

我正在使用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来过滤查询集?

django django-models django-queryset
1个回答
0
投票

您是否尝试过过滤关系的属性?

user = User.objects.prefetch_related(
    'relation'
).filter(
    relation__status='active'
).get(pk=request.user.pk)
© www.soinside.com 2019 - 2024. All rights reserved.