【发布时间】:2019-10-08 14:02:25
【问题描述】:
如果仅与其父对象相关的子对象具有数据,我想过滤并仅获取与其相关对象数据相关的那些数据。例如: 我有以下型号:
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 |
+--------+------------------+-----------------------+
这里我的价格仅与 1 和 3 产品相关,所以我只想要那些基于查询集的产品,我只想根据特定的 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)
是我做的方式还是下一个方式..它有时会产生不好的结果。我该怎么做。
【问题讨论】:
标签: python django django-2.0