无法使用pre_save信号在django模型中保存相关对象

时间:2018-05-22 20:29:37

标签: python django python-3.x

我必须在Django ORM中实现multi-aspect type of inheritance from UML。我有Contract数据类型,根据客户类型(常规客户或商业客户),可以归类为RegularContractBusinessContract。合同也可以具有到期日期或不可过期(未指定有效期多长),因此它也可以是ExpiringContractNonExpiringContract类型。这是概念图的外观: enter image description here

这就是我实现此目的的方式:enter image description here

models.py 代码:

class Contract(models.Model):
    approval_date = models.DateTimeField(null=False)

    def __getattr__(self, item):
        if self.expiringcontract:
            return getattr(self.expiringcontract, item)
        elif self.nonexpiringcontract:
            return getattr(self.nonexpiringcontract, item)


class ContractExpirationExtension(models.Model):
    base = models.OneToOneField("website.Contract",
                                on_delete=models.CASCADE)

    class Meta:
        abstract = True


class ExpiringContract(ContractExpirationExtension):
    termination_date = models.DateTimeField()

    @property
    def duration(self):
        return self.termination_date - self.base.approval_date


class NonExpiringContract(ContractExpirationExtension):

    @property
    def duration(self):
        return timedelta(days=100)


class ContractTypeExtension(models.Model):

    base = models.OneToOneField("website.Contract", on_delete=models.CASCADE)
    termination_delay = models.PositiveSmallIntegerField(default=30)

    class Meta:
        abstract = True

    @classmethod
    def create(cls, approval_date, contract_expiration_type, termination_delay, **kwargs):
        type_extension = cls(termination_delay=termination_delay)
        base = Contract(approval_date=approval_date)
        expiration_type = contract_expiration_type(**kwargs)
        expiration_type.base = base
        type_extension.base = base
        if contract_expiration_type.__name__ == ExpiringContract.__name__:
            type_extension.base.expiringcontract = expiration_type
        elif contract_expiration_type.__name__ == NonExpiringContract.__name__:
            type_extension.base.nonexpiringcontract = expiration_type
        return type_extension

    def __getattr__(self, item):
        if self.base:
            return getattr(self.base,item)


class RegularContract(ContractTypeExtension):
    termination_delay = models.PositiveSmallIntegerField(validators=[validate_term_delay_regular], blank=False)


class BusinessContract(ContractTypeExtension):
    termination_delay = models.PositiveSmallIntegerField(validators=[validate_term_delay_business], blank=False)

当我们需要创建新的合同模型实例时,我们使用继承create()抽象类的类的ContractTypeExtension方法。在create()方法中,我创建Contract基本实例和基于类对象参数的合适的到期或非到期合同实例,我传递给create()方法:

@classmethod
def create(cls, approval_date, contract_expiration_type, termination_delay, **kwargs):
    type_extension = cls(termination_delay=termination_delay)
    base = Contract(approval_date=approval_date)
    expiration_type = contract_expiration_type(**kwargs)
    expiration_type.base = base
    type_extension.base = base
    if contract_expiration_type.__name__ == ExpiringContract.__name__:
        type_extension.base.expiringcontract = expiration_type
    elif contract_expiration_type.__name__ == NonExpiringContract.__name__:
        type_extension.base.nonexpiringcontract = expiration_type
    return type_extension

因为我的常规或业务合同实例中包含其他模型实例,所以我无法保存它而不先保存baseexpiration_type实例,因此我决定创建pre_save信号这将完全是这样:

signals.py

from django.db.models.signals import pre_save, pre_delete from django.dispatch import receiver

from .models import RegularContract, BusinessContract

@receiver(pre_save, sender=RegularContract) 
@receiver(pre_save, sender=BusinessContract) 
def pre_save_contract(sender, instance, *args,**kwargs):
    print("Pre_save")
    if not instance.id:
        instance.base.save()
        try:
            instance.base.expiringcontract.save()
        except (TypeError, ValueError):
            instance.base.nonexpiringcontract.save()

我在app __init__apps.py config:

中注册了我的信号文件

apps.py

from django.apps import AppConfig


class WebsiteConfig(AppConfig):
    name = 'website'

    def ready(self):
       import website.signals

网站.__初始化__吡啶

default_app_config = 'website.apps.WebsiteConfig'

为了测试我的代码,我编写了简单的测试用例:

class BusinessContractTestCase(TestCase):

    def setUp(self):
        pass

    def test_exprirating_creation(self):
        approval_date = datetime.today()
        termination_delay = 30
        termination_date = approval_date+timedelta(days=720)
        contract = BusinessContract.create(approval_date=approval_date,                                                         contract_expiration_type=ExpiringContract,
                                      termination_delay=termination_delay,
                                       termination_date=termination_date)
        contract.save()
        self.assertEqual(contract.termination_date.date(), ExpiringContract.objects.first().termination_date.date())


class RegularContractTestCase(TestCase):

    def test_exprirating_creation(self):
        approval_date = datetime.today()
        termination_delay = 30
        termination_date = approval_date + timedelta(days=720)
        contract = RegularContract.create(approval_date=approval_date,
                                      contract_expiration_type=ExpiringContract,
                                      termination_delay=termination_delay,
                                      termination_date=termination_date)
        contract.save()
        self.assertEqual(contract.termination_date.date(),
                           ExpiringContract.objects.first().termination_date.date())

但是当尝试运行此测试时,它们会失败并且我收到此错误:

Error
Traceback (most recent call last):
File "/home/ubuntu/workspace/webapp/website/tests.py", line 21, in test_exprirating_creation
contract.save()
File "/home/ubuntu/workspace/venv/lib/python3.5/site-packages/django/db/models/base.py", line 685, in save
"unsaved related object '%s'." % field.name
ValueError: save() prohibited to prevent data loss due to unsaved related object 'base'.

那么为什么我的代码中没有触发pre_save信号?

1 个答案:

答案 0 :(得分:0)

经过简短的调试后,我理解了我的问题(感谢Willem Van Onsem指出pre_save的详细信息。)这就是我解决它的方法。我略微修改了create()方法。不是将base直接分配给新创建的实例,而是将expiration_type分配给基础,而是将它们保存到临时变量中,以后可以在我的信号方法中使用:

@classmethod
def create(cls, approval_date, contract_expiration_type, termination_delay, **kwargs):
    type_extension = cls(termination_delay=termination_delay)
    base = Contract(approval_date=approval_date)
    expiration_type = contract_expiration_type(**kwargs)
    type_extension.temp_base = base
    if contract_expiration_type.__name__ == ExpiringContract.__name__:
        type_extension.temp_expiringcontract = expiration_type
    elif contract_expiration_type.__name__ == NonExpiringContract.__name__:
        type_extension.base.temp_nonexpiringcontract = expiration_type
    return type_extension

然后在signals.py pre_save信号中,我分别从临时变量中保存base并分配给实例的base,并将我的expiring / nonexpiring契约类型实例从临时变量分别分配给base并保存:

@receiver(pre_save, sender=RegularContract)
@receiver(pre_save, sender=BusinessContract)
def pre_save_contract(sender, instance, *args, **kwargs):
    print("Pre_save")
    instance.temp_base.save()
    instance.base = instance.temp_base
    if hasattr(instance,"temp_expiringcontract"):
        instance.base.expiringcontract = instance.temp_expiringcontract
        instance.base.expiringcontract.save()
    else:
        instance.base.nonexpiringcontract =    instance.temp_nonexpiringcontract
        instance.base.nonexpiringcontract.save()

这可能不是最好的解决方案,但至少它可行。