【问题标题】:custom foreign key values based on constrain基于约束的自定义外键值
【发布时间】:2019-01-14 02:27:54
【问题描述】:

我有一个模型:

PRODUCT_EXPIRY 型号:

product_id = model.IntegerField()
expires_in = model.IntegerField() --days count

另一个模型为:

产品:

product_id = model.IntegerField()
expires_in = model.IntegeField(blank=True)  --days count
name = model.CharField()
price = model.FloatField()
...other fields

我想要的是,让一个商店添加产品,这里expires_in(天数)的产品是可选的,他可以选择在添加产品时手动添加,或者如果他不添加,那么过期时间是从product_expire 模型输入,通过product_id 映射。

但是考虑以下情况:

  1. Milk X 有 3 天的保质期。
  2. 牛奶 Y 有 60 天的保质期。
  3. 可可粉的保质期为 6 个月。

当商店输入产品时,假设他至少在生产日期后 10 天后收到它。因此,添加可可粉时的expire_in 应为60-10 = 50 days,即有效期超过 30 天的产品。由于牛奶车每天运送牛奶,因此有效期少于 30 天的产品将具有相同的有效期而没有任何更改,即添加牛奶 expires_in 为牛奶 X 将是 3 days。我该怎么做? Product 模型 expired_in 必须是外键吗?

例如: 假设我们知道可乐在 1 个月后过期,那么如果商店忘记输入过期日期,则添加的自动过期日期应为 20 天。因此,如果产品即将过期,我可以通知商店。但对于牛奶到期添加应无任何变化。
或者我是否必须通过覆盖产品模型的保存功能为此构建自定义算法?

我现在的想法是:

  • 将其保留为IntegerField,并添加另一个字段为DateTime, 如果输入日期时间字段,则使用该字段,否则使用 expired_in 字段,并覆盖保存功能。
  • 稍后通过 pandas 或一些自定义 python 脚本处理空白值。 但是有没有简单的方法?

【问题讨论】:

  • 更好地使用到期日期,然后您可以计算剩下多少天想象一个员工计算产品到期还有多少天......它会减慢条目,更好地使用到期日期

标签: django database algorithm django-models foreign-keys


【解决方案1】:

我看到的模型应该是这样的

class Product(models.Model):
    """
    """
    class Meta:
        verbose_name = _("Procuct")
        verbose_name_plural = _("Products")
    quantity = model.IntegeField() #Imagine ther are 50 packs of coffe that have arrived today
    name = models.CharField(max_length=255, verbose_name=_("name"))
    prise = FloatField()
    expiry_date = models.DateField()
    arrived_at = models.DateField()
    status = 'not_expired'


    def __str__(self):
        return '{name} {expiry_date}'.format(name=self.name, expiry_date=self.expiry_date)

最好使用到期日期而不是 exprites_in,因为如果员工应该输入所有内容而不是只输入到期日期会更耗时

那么,如果您想查看将在接下来的 5 天到期的产品,只需

进口日期

def checkExpiringProducts(days)
    return Products.objects.filter(status='not_expired',expiry_date__lte=date.today()+datetime.timedelta(days=days)

如果你打电话

checkExpiringProducts(5)#gives you the products that are expiring next 5 days

您应该输入status,并每天检查今天或明天是否有带有expiry_date 的产品以使其成为status expired

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 2013-07-29
    • 2020-10-16
    • 1970-01-01
    • 2019-01-09
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多