0

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

4

2 回答 2

3

根据文档,您无法过滤已缓存的对象。但是,您可以在使用Prefetch获取对象时将它们过滤掉。它也在 django 3.1 中工作。例如:

from django.db.models import Prefetch

user = User.objects.get(pk=request.user.pk).prefetch_related(
  Prefetch('relation', queryset=Relation.objects.filter(status='active'))
)
于 2020-11-11T01:02:40.873 回答
-1

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

user = User.objects.prefetch_related(
    'relation'
).filter(
    relation__status='active'
).get(pk=request.user.pk)
于 2020-05-31T20:30:25.293 回答