Django - 模型结构
Django - model structure
我是 Django 的新手,我的模型结构遇到了问题:
我有一个模型 Item
代表很多待售物品。
有些项目有 tag
。有些人没有。
谁有tag
,谁就有同样的percentage
折扣:五个选项供用户选择(5%、10%、15%、20%、25%);
当 administrator/user 将折扣从 5% 增加到 15% 时,所有带有标签的商品都会有相同的 15% 折扣。
我不确定我是否应该设置一个布尔值 tag
字段,然后为 percentage
或什至另一个托管折扣 percentage
选择的模型设置另一个字段,或者我应该只是为 percentage
设置标签选项的 IntegerField?但是如何保持所有具有相同标签的项目同步呢?有没有消耗资源最少的方法?
您可以创建一个引用 Tag
模型的可空字段,并让 Tag
模型包含百分比。例如:
from decimal import Decimal
class Tag(models.Model):
percentage = models.DecimalField(max_digits=2, decimal_places=2)
class Item(models.Model):
# …
discount_tag = models.ForeignKey(Tag, on_delete=models.PROTECT, null=True)
@property
def discount(self):
if self.discount_tag is not None:
return self.discount_tag.percentage
return Decimal()
因此我们可以在这里添加一个 @property
来检查 Item
是否有相关标签,如果有,它 returns percentage
discount_tag
。否则,它 returns Decimal('0')
.
我是 Django 的新手,我的模型结构遇到了问题:
我有一个模型 Item
代表很多待售物品。
有些项目有 tag
。有些人没有。
谁有tag
,谁就有同样的percentage
折扣:五个选项供用户选择(5%、10%、15%、20%、25%);
当 administrator/user 将折扣从 5% 增加到 15% 时,所有带有标签的商品都会有相同的 15% 折扣。
我不确定我是否应该设置一个布尔值 tag
字段,然后为 percentage
或什至另一个托管折扣 percentage
选择的模型设置另一个字段,或者我应该只是为 percentage
设置标签选项的 IntegerField?但是如何保持所有具有相同标签的项目同步呢?有没有消耗资源最少的方法?
您可以创建一个引用 Tag
模型的可空字段,并让 Tag
模型包含百分比。例如:
from decimal import Decimal
class Tag(models.Model):
percentage = models.DecimalField(max_digits=2, decimal_places=2)
class Item(models.Model):
# …
discount_tag = models.ForeignKey(Tag, on_delete=models.PROTECT, null=True)
@property
def discount(self):
if self.discount_tag is not None:
return self.discount_tag.percentage
return Decimal()
因此我们可以在这里添加一个 @property
来检查 Item
是否有相关标签,如果有,它 returns percentage
discount_tag
。否则,它 returns Decimal('0')
.