【问题标题】:What is best way to add product features in django with database mysql使用数据库 mysql 在 django 中添加产品功能的最佳方法是什么
【发布时间】:2020-02-18 05:03:56
【问题描述】:

我想将产品功能存储在 MySQL 数据库中,所以我对哪种方式更好地存储它以获得更好的性能和可扩展性有些困惑。

基本上按照我的想法,我设计了如下所示的模型:其中,我有一个产品表,其中包含字段产品类型的功能表,其中产品类型属于该特定功能。最后一张表是 product_features,因为我实际上存储了特定 product_id 和 feature_id 的数据,这是正确的方式吗?

我正在使用 Django。这是我的模型!

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    product_name = models.CharField(max_length=255, null = False, unique=True)
    product_slug = models.SlugField(unique=True, blank=True, null=True)
    product_title = models.CharField(max_length=255, null = True)
    product_info = models.TextField(null = False)
    product_description = models.CharField(max_length = 255)
    product_price = models.CharField(max_length = 255)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    product_status = models.CharField(max_length = 100, default = "publish")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Feature(models.Model):
    feature_id = models.AutoField(primary_key=True)
    feature_name = models.CharField(max_length=255, null = False)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    feature_has_value = models.CharField(max_length = 1, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product_feature(models.Model):
    product_feature_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    product_feature_value = models.CharField(max_length=255, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

【问题讨论】:

  • 多个产品是否使用相同的功能?您是否要更新此功能并且它同样适用于所有产品?
  • @danblack 实际上我还有 1 个称为产品类型的模型,因为我有一些类型,如会计软件、学校管理软件等,所以每种产品类型都有它们的功能,并且在产品表中我已经关联的产品类型。

标签: mysql django database django-models


【解决方案1】:

根据我的想法,您的模型看起来很适合产品功能,除了所有模型中的主键字段,无需在 django 模型中管理 primary key,因为 django 已经将每个模型的 id 字段管理为 primary key

第二件事通常是很多时候在线购物网站上的特定产品会有折扣,所以如果你的计划也是这样,那么你也可以在你的应用程序中添加一个折扣模型。

【讨论】:

  • 感谢您的建议,您认为明确使用 id 字段不是很好吗?但我认为 Django 将字段命名为唯一的 id,因此在处理多个表时有点混乱
  • 根据您的说法,这是一个好方法还是将来会产生问题?
  • 不,以后不会有任何问题,因为如果你想使用任何对象的id,那么你可以直接使用model_object.id。因此,识别id 不会造成任何类型的混淆,因为它也会通过其model_object 变量来识别。
  • 是的!感谢@MK Patel 的帮助
  • 总是...快乐编码:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 2010-09-14
  • 2020-01-22
  • 1970-01-01
  • 2012-04-08
相关资源
最近更新 更多