【问题标题】:Django, how to set a filter based on a queryset?Django,如何根据查询集设置过滤器?
【发布时间】:2020-07-08 17:05:14
【问题描述】:

我有一个由三个不同模型给出的查询集:

class Sottocategoria(models.Model):
    name = models.CharField('Nome del sottoprodotto', max_length=30)

class A(models.Model):
    codice_commessa=models.ForeignKey()
    prodotto=models.ForeignKey()
    sottocategoria=models.ForeignKey(Sottocategoria)

class B(models.Model):
    quantity=models.ForeignKey()
    price=models.DecimalField()
    sottocategoria=models.ForeignKey(Sottocategoria)

现在我设置了以下 for 循环:

for sottocategoria_id, totale in 
 (B.objects.values_list('sottocategoria__id').annotate(totale=(Sum(F('quantity') * F('price')))):
....

我需要过滤模型 B 中的 sottocategoria__id,它们存在于模型 A 中。

广告示例如果我在 model A sottocategoria 中等于 {'abc','abcd','abcdf'} 并且模型 B sottocategoria 等于 {'abc','abcd','abcdf', '1234'},则在我的 for 循环中我只想过滤 {'abc','abcd','abcdf'}

【问题讨论】:

  • 'abc'等是什么?名字?
  • 是的,是 Sottocateoria 模型的名称

标签: python python-3.x django django-models django-views


【解决方案1】:

您可以使用__in lookup [Django-doc] 进行过滤:

B.objects.filter(
    sottocategoria__name__in={'abc','abcd','abcdf'}
).values_list(
    'sottocategoria_id'
).annotate(
    totale=Sum(F('quantity') * F('price'))
)

您还可能想要.order_by('sottocategoria_id'),这样如果您下标,您将在sottocategoria_id 上下标,而不是在B 对象的主键上:

B.objects.filter(
    sottocategoria__name__in={'abc','abcd','abcdf'}
).values_list(
    'sottocategoria_id'
).annotate(
    totale=Sum(F('quantity') * F('price'))
).order_by('sottocategoria_id')

例如,如果您查找被A 引用的sottocategorias,您可以使用:

B.objects.filter(
    sottocategoria__in=Sottocategoria.objects.filter(a__isnull=False).distinct()
).values_list(
    'sottocategoria_id'
).annotate(
    totale=Sum(F('quantity') * F('price'))
).order_by('sottocategoria_id')

对于某些数据库,例如 MySQL,最好先实现 id:

sottocategoria_ids = list(Sottocategoria.objects.filter(a__isnull=False).values_list('pk', flat=True).distinct())

B.objects.filter(
    sottocategoria__in=sottocategoria_ids
).values_list(
    'sottocategoria_id'
).annotate(
    totale=Sum(F('quantity') * F('price'))
).order_by('sottocategoria_id')

我们也可以从A模型中查询:

sottocategoria_ids = list(A.objects.values_list('sottocategoria_id', flat=True).distinct())

B.objects.filter(
    sottocategoria__in=sottocategoria_ids
).values_list(
    'sottocategoria_id'
).annotate(
    totale=Sum(F('quantity') * F('price'))
).order_by('sottocategoria_id')

【讨论】:

  • 好的,谢谢,但是“名称”变量会发生变化并且不固定。是客户可以根据自己的喜好填写的字段
  • @FedericoDeMarco:然后你会得到这些,例如从 request.GET.getlist(...) 参数中。如果您使用表单 (docs.djangoproject.com/en/3.0/topics/forms),它可能会更简单。所以{'abc', ...} 中的值不需要硬编码,它们可以来自任何你想要的地方。
  • {'abc','abcd','abcdf'} 只是一个例子,我不知道它们的价值
  • @FedericoDeMarco:好吧,如果你用 HTML 制作表单或其他东西,那么你可以使用它作为提供值的机制。
  • 好吧,实际上我想从模型 A 中提取它们并根据它们过滤模型 B。我有一个填写数据库的表格。之后我想提取这个值并用它们来过滤模型 B
猜你喜欢
  • 1970-01-01
  • 2022-07-19
  • 2020-11-13
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 2020-08-01
相关资源
最近更新 更多