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

时间:2020-05-12 11:22:04

标签: django django-models django-queryset

我正在使用 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答案https://stackoverflow.com/a/12609454/3719167

中的prefetch_related获取max

是否可以使用lambda来过滤查询集?

2 个答案:

答案 0 :(得分:2)

根据documentation,您无法过滤已缓存的对象。但是,您可以在使用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'))
)

答案 1 :(得分:0)

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

user = User.objects.prefetch_related(
    'relation'
).filter(
    relation__status='active'
).get(pk=request.user.pk)