首页 > 解决方案 > 如果查询集包含django中的数据,如何根据相关对象过滤查询集

问题描述

如果仅与其父对象相关的子对象具有数据,我想过滤并仅获取与其相关对象数据相关的那些数据。例如:我有以下型号:

class Collection(models.Model):
    date_of_collection=models.DateField()

class Product(models.Model):
    name=models.CharField(max_length=100)
    collection = models.ForeignKey(Collection)

class Price(models.Model):
    price = models.FloatField()
    products = models.ForeignKey(Products, on_delete=models.CASCADE)

我有与模型相关的数据:

Collection:
+----+--------------------+
| id | date_of_collection |
+----+--------------------+
|  1 | 2019-01-17         |
|  2 | 2019-01-30         |
|  3 | 2019-02-01         |
|  4 | 2019-02-02         |
+----+--------------------+

Products:

 +----+--------------------------------+
 | id | name           | collection    |
 +----+--------------------------------+
 |  1 | product 1      | 3             |
 |  2 | product 2      | 1             |
 |  3 | product 3      | 1             |
 |  4 | product 4      | 4             |
 +----+--------------------------------+

Price:

| id     | price            | product               |
+--------+------------------+-----------------------+
| 1      | 10.00            | 1                     |
| 2      | 20.00            | 1                     |
| 3      | 12.00            | 3                     |
+--------+------------------+-----------------------+

在这里,我只有13产品相关的价格,所以我只想要那些基于查询集的产品,我只想根据特定的 date_of_collection 进行过滤。

我尝试了以下查询集:

collection_month = Collection.objects.filter(date_of_collection__month=2)
product = Product.objects.filter(collection_id__in=collection_month).exclude(price_set__price=None)

是我做的方式还是下一个方式..它有时会产生不好的结果。我该怎么做。

标签: pythondjangodjango-2.0

解决方案


你很接近。
您不应该collection_id与实际的收藏品进行比较 - 您可以通过collection__in=collection_month.
您可以直接排除产品而无需price使用price__isnull=True

此查询将使用子查询 ( WHERE):

collection_month = Collection.objects.filter(date_of_collection__month=2)
products = Product.objects.filter(collection__in=collection_month).exclude(price__isnull=True)

此查询将使用INNER JOIN传闻更快的方法

products = Product.objects.filter(collection__date_of_collection__month=2).exclude(price__isnull=True)

推荐阅读