我需要存储客户忠诚卡。
它应该是灵活的。我有几种具有不同折扣系统的卡变体。
例如,卡按购买金额 - > $100 - 5%、> $1000 - 10% 等。或者按访问金额 - > 10 - 3%、100 - 10% 等
此外,它应该存储不同类型的卡和销售额的不同图像,例如5% - 银色,10% - 金色等。
我想出了以 JSON 形式存储在数据库中的想法。
访问例如:
schema = {1: {'discount': 5%, image: '....', 'style': {'background': ..., 'foreground': ...},
2: {'discount': 10%, image: '....', 'style': {'background': ..., 'foreground': ...},
3: {'discount': 15%, image: '....', 'style': {'background': ..., 'foreground': ...},
}
class ABSCard(models.Model):
title = field
work_place = field
....
class Discount(models.Model):
type = ....
schema = JSONField
abscard_id = ABSCard
但我不确定在 PostgreSQL 中存储 JSON 是最好的方法。
如果我是你,我会使用模型为不同类型的折扣创建架构,然后我会在数据库中为不同的折扣创建实际对象。
这是我对模型进行编码的方法:
from django.utils.translation import gettext_lazy as _
# enumerator for field in model below
class DISCOUNT_TYPES(models.IntegerChoices):
VOLUME = 0, _("Volume")
VISIT = 1, _("Visit")
# enumerator for field in model below
class STYLING_CLASSES(models.IntegerChoices):
GOLD = 0, _("Gold")
SILVER = 1, _("Silver")
BRONZE = 2, _("Bronze")
class Discount(models.Model):
discount_percentage = PositiveSmallIntegerField
discount_type = PositiveSmallIntegerField(choices=DISCOUNT_TYPES, default=DISCOUNT_TYPES.VOLUME)
amount_to_spend = PositiveSmallIntegerField(null=True, blank=True)
num_visits = PositiveSmallIntegerField(null=True, blank=True)
css_class = CharField(choices=STYLING_CLASSES, default=STYLING_CLASSES.BRONZE)
# or instead of img URL you could do a FileField if you want to store the static image yourself
img_url = URLField
class Card(models.Model):
name = CharField(max_length=60)
# or if you want multiple discounts associated with a card, you could use a ManyToManyField here instead
discount = ForeignKeyField(Discount, on_delete=models.CASCADE)
通过这种方式,您可以将一个或多个折扣(
Discount
模型对象)与任何给定的Card
模型对象相关联。这使您可以灵活地在以后进行自定义。例如,您可以创建名为 UserLoyaltyCard
的第三个模型,它关联一个 Card
对象(区别在于 Card
对象是通用的,但 UserLoyaltyCard
可以具有 User
外键字段和 ID_number
字段,例如)。
注意上面的
Discount
模型有一个简单的 css_class
字段。这样,您的 CSS 定义将存在于静态 CSS 文件中(如果这只是后端 API,则存在于您的前端),这才是样式真正应该存在的位置,而不是存在于您的数据库中。