【问题标题】:Overrinding a field in different table on django在 django 上覆盖不同表中的字段
【发布时间】:2020-12-02 10:03:21
【问题描述】:

我希望在保存新订单时将 order.id_order 保存在 company.last_order 上

class Company(models.Model):
    name = models.CharField(max_length=240)
    last_order = models.DecimalField(max_digits=20, decimal_places=0)

class Order(models.Model):
    company = models.ForeignKey('Company', on_delete=models.CASCADE)
    id_order = models.DecimalField(max_digits=20, decimal_places=0)

【问题讨论】:

    标签: django django-models django-views django-forms


    【解决方案1】:

    您可以覆盖 Order 类的 save(...) 方法

    class Order(models.Model):
        company = models.ForeignKey('Company', on_delete=models.CASCADE)
        id_order = models.DecimalField(max_digits=20, decimal_places=0)
    
        def save(self, *args, **kwargs):
            created = not self.pk
            super().save(*args, **kwargs)
            if created:
                Company.objects \
                    .filter(pk=self.company_id) \
                    .update(last_order=self.id_order)

    【讨论】:

    • 干得好,请问有什么想法可以为每个公司设置一个唯一的 id_order 吗? id 为 ex 1, 2, 3 ... 的公司 A 订单,但不能有两次订单 3。公司 B 的 id 订单为 ex 10、20、30 ...,但不能两次订购 30。或者换一种说法,如果这个 company.id_order 已经存在,就不能再保存了
    • 您似乎在搜索unique=True。如果没有,最好单独问一个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 2020-07-26
    • 2012-02-06
    • 2013-07-06
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多