[英]Django, how to set a filter based on a queryset?
我有一个由三个不同模型给出的查询集:
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
,这些模型存在于 model A 中。
广告示例 如果我在model A
sottocategoria 等于{'abc','abcd','abcdf'}
和 model B sottocategoria 等于{'abc','abcd','abcdf', '1234'}
,我的 for 循环我只想过滤{'abc','abcd','abcdf'}
。
您可以使用__in
查找 [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
object 的主键上下标:
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
引用的sottocategoria
,您可以使用:
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
model查询:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.