Django使用ManyToMany过滤了多次映射

时间:2018-10-11 07:50:58

标签: python django

假设我的模型中有类似的内容。py:

Warning  ProvisioningFailed    1m (x12 over 1m)  openebs.io/provisioner-iscsi openebs-provisioner-57cb7b7645-d64gg 4dd1d524-ca93-11e8-afd9-6a03d5095334  Failed to provision volume with StorageClass "openebs-1repl": Internal Server Error: failed to create volume 'monitoring-elasticsearch-data-eskeim-elasticsearch-0-2504067681': response: Service "monitoring-elasticsearch-data-eskeim-elasticsearch-0-2504067681-ctrl-svc" is invalid: metadata.name: Invalid value: "monitoring-elasticsearch-data-eskeim-elasticsearch-0-2504067681-ctrl-svc": must be no more than 63 characters

我想获得一个与B映射了多个时间的A。

2 个答案:

答案 0 :(得分:0)

我们可以用数量A注释B个对象,然后根据该数量进行过滤,例如:

from django.db.models import Count

A.objects.annotate(
    n_b=Count('b')
).filter(n_b__gt=1)

因此,所有A对象都用属性.n_b(相关B的数量)注释,然后我们进行过滤,以使该数量n_b大于(__gt个。

然后产生一个查询,如:

SELECT a.*, COUNT(a_b.b_id) AS n_b
FROM a
LEFT OUTER JOIN a_b ON a_b.a_id = a.id
GROUP BY a.id
HAVING COUNT(a_b.b_id) > 1

答案 1 :(得分:0)

B.A.through.objects.filter(name="a") can you try this.