【发布时间】:2021-09-01 05:14:16
【问题描述】:
我有 2 个表(Product 和 CustomerProduct)
CustomerProduct 是 Customer 和 Product 之间的中间表。它将客户特定的定价分配给某些产品。
产品型号
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=12, decimal_places=2)
样本数据
| id | name | price |
|---|---|---|
| 1 | orange | 1.5 |
| 2 | apple | 2.2 |
| 3 | kiwi | 3.5 |
客户产品模型
class CustomerProduct(models.Model):
customer = models.ForeignKey(
"Customer",
on_delete=models.CASCADE,
related_name="customer_customerproducts",
)
product = models.ForeignKey(
"Product",
on_delete=models.CASCADE,
related_name="product_customerproducts",
)
price = models.DecimalField(
max_digits=12,
decimal_places=2,
)
样本数据
| id | customer_id | product_id | price |
|---|---|---|---|
| 1 | 233 | 1 | 1.2 |
| 2 | 233 | 2 | 2.0 |
预期结果
如果相关字段存在,我想查询除 Product.price 根据 CustomerProduct.price 调整的所有产品。预期数据(json 中的示例但需要查询集):
[
{
id: 1
name: "orange"
price: 1.2 // The price adjusted according to customer price
}
{
id: 2
name: "apple"
price: 2.0 // The price adjusted according to customer price
}
{
id: 3
name: "kiwi"
price: 3.5 // Price remain original because CustomerProduct not exists.
}
]
方法
我完全不知道如何在 Django 中实现这一点。该怎么做?
【问题讨论】:
-
您的型号代码会很有帮助...
-
@AbdulAzizBarkat 你的意思是不够有帮助?介意让我知道哪个型号,我改变它。 tqvm
-
我的意思是说请edit 并将您的模型代码添加到问题中......(当然,您有一些类似于
class Product(models.Model): ...的代码,我想说这与您的高度相关问题) -
@AbdulAzizBarkat 是有道理的。更新
标签: sql django postgresql django-models