在这种情况下可以覆盖 Django 模型的保存功能吗?

问题描述 投票:0回答:0

所以,我有一个模型,它的保存功能有一些像这样的副作用:

from django.db import models

class Customer(models.Model):
    customer_name = models.CharField(max_length=255)
    customer_email = models.EmailField()
    customer_phone = models.CharField(max_length=20)
    customer_address = models.CharField(max_length=255)

class Product(models.Model):
    product_name = models.CharField(max_length=255)
    product_description = models.TextField()
    product_price = models.DecimalField(max_digits=10, decimal_places=2)

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    order_date = models.DateField()
    order_total = models.DecimalField(max_digits=10, decimal_places=2)

class Order_Item(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    item_price = models.DecimalField(max_digits=10, decimal_places=2)

class User(models.Model):
    username = models.CharField(max_length=255)
    email = models.EmailField()
    password = models.CharField(max_length=255)

class OrderFolder(models.Model):
    REASON_ARCHIVED = 'ARCHIVED'
    REASON_REVIEW = 'REVIEW'
    REASON_CHOICES = [
        (REASON_ARCHIVED, 'Archived'),
        (REASON_REVIEW, 'Review'),
    ]
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    reason = models.CharField(max_length=10, choices=REASON_CHOICES)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

class Payment(models.Model):
    payment_date = models.DateField()
    payment_amount = models.DecimalField(max_digits=10, decimal_places=2)
    payment_method = models.CharField(max_length=50)
    order = models.ForeignKey('Order', on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
      super(Payment, self).save(*args, **kwargs)

      # If order is paid and order is not in review, move it to the ARCHIVED folder
      if self.order.order_total == self.payment_amount:
        of = OrderFolder.objects.get(pk = self.order.id)
        if of.reason != 'Review':
          of.reason = 'ARCHIVED'
          of.save()

在上面的代码中,我覆盖了 Payment 的保存方法以在另一个表中产生副作用。 Django 允许覆盖 save 方法,但考虑到这种方法是否可以接受:

  1. 可能会破坏 SOLID 设计中的单一职责原则
  2. 可能引入紧耦合。
  3. 在模型的保存中引入业务逻辑
django django-models solid-principles system-design single-responsibility-principle
© www.soinside.com 2019 - 2024. All rights reserved.