Django通过其相关模型列表筛选模型。

huangapple go评论57阅读模式
英文:

Django filter model by it's related model list

问题

以下是翻译好的部分:

有一个包含 n+1 个产品的采购订单
我想通过其中的产品来筛选采购订单
在查找采购订单的搜索过程中查询集应返回所有包含itemA和itemB的采购订单

模型类
```python
class PurchaseOrder:
    id = ....

class Product:
    purchase_order = models.ForeignKey(PurchaseOrder, related_name='product')

作为输入值的查找值是产品的ID列表,例如我们取 q = [1,3,5]

结果需要所有包含product1、product2、product3的采购订单。

我尝试过类似于这样的代码,但它没有返回任何结果。

   q_objects = (Q(product__in=query[0]), Q(product__in=query[1]))
   qs = self.filter(q_objects)

作为额外的解决方案,因为我认为会消耗大量资源,所以在代码中没有实现:

  1. 返回包含product1的采购订单的查询。
    再次循环,这次检查采购订单是否包含product2,然后保留以供进一步验证。然后继续处理来自列表的所有产品ID。

  2. 通过使用django信号,在每次保存信号时,在文本字段中以逗号分隔的方式保存所有产品ID。然后将其与q进行比较。

这目前是实施的第一阶段。稍后还需要按数量进行过滤。
例如,如果q = [1,1,3,5],将返回所有包含两个产品1和每个产品3和产品5的产品。

英文:

There is purchase orders which contains n+1 products.
I want to filter PurchaseOrder by products in it.
In search process for looking up PurschaseOrders query set should return all purchase orders where there are itemA and itemB in it.

Modell classes

class PurchaseOrder:
    id = ....

class Product:
    purchase_order = models.ForeignKey(PurchaseOrder, related_name='product')

For lookup as input values I have list of Product id's, for example lets take q = [1,3,5]

As result I need all Purchase orders, which contains product1, prodcut2, product3.

I have tried something like this, but it doesn't return any result.

   q_objects = (Q(product__in=query[0]), Q(product__in=query[1]))
   qs = self.filter(q_objects)

As additional solution, which is not done in the code, because in opinion can cost a lot of resources:
1.return query of purchase orders, which contain product1.
Looping trough again, this time checking if Purchase orders contain product2, then keep for further validation. And keep the process with product all ids, from list.

  1. by using django signals, which on each save signal, saves all product id's comma separated in text field. Which is compared with q

This currently is first level of implementation. Later it would be necessary to filter also by count.
For example if q =[1,1,3,5] will return all products, where there are two products1 and one for each product3 and product5.

答案1

得分: 0

你可以使用以下代码进行筛选:

from django.db.models import Count

ids = [1, 3, 5]
PurchaseOrder.objects.filter(product_id__in=qs).alias(
    nproducts=Count('product')
).filter(nproducts=len(set(ids)))
英文:

You can filter with:

<pre><code>from django.db.models import Count

ids = [1, 3, 5]
PurchaseOrder.objects.filter(<b>product_id__in=qs</b>).alias(
<b>nproducts=Count('product')</b>
).filter(nproducts=len(set(ids)))</code></pre>

huangapple
  • 本文由 发表于 2023年2月7日 03:21:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定