【问题标题】:Massage model data before save in Django在 Django 中保存之前按摩模型数据
【发布时间】:2011-11-29 05:53:17
【问题描述】:

我不确定这是否是最好的方法,但我有一些数据正在通过表单发送。我有一个ModelForm,它采用该表单数据的request.POST。发送的所有数据都是描述、金额和存款(布尔值)。

当人提交数据时,金额将为正数,但如果存款为假,我想将其作为负数存储在数据库中。

我正在考虑在 Model 或 ModelForm 中执行此操作,并在保存之前对该数量进行按摩...因此,在其中一个类中的某个地方,我想要类似的东西:

if not deposit:
    amount = -amount

...然后按原样保存。

有没有办法在 ModelForm 或 Model 中处理这个问题,让我不必在视图中执行所有这些逻辑?

【问题讨论】:

    标签: python django forms model


    【解决方案1】:

    ModelForm 的 save() 方法是一个很好的地方:

    class MyForm(models.ModelForm):
        ...
        def save(self):
            instance = super(MyForm, self).save(commit=False)
            if not self.deposit:
                self.amount = -self.amount
            instance.save()
            return instance
    

    【讨论】:

      【解决方案2】:

      覆盖模型保存方法是一种解决方案。但我不喜欢以干净的方法进行此操作并将其与业务规则混合:

      models.py:

      from django.db import models 
      class Issue(models.Model):
          ....
          def clean(self): 
              rules.Issue_clean(self)
      
      from issues import rules
      rules.connect()
      

      rules.py:

      from issues.models import Issue
      def connect():
      
          from django.db.models.signals import post_save, pre_save, pre_delete
          #issues 
          pre_delete.connect(Issue_pre_delete, sender= Incidencia) 
          pre_save.connect(Issue_pre_save, sender = Incidencia ) 
          post_save.connect(Issue_post_save, sender = Incidencia )
      
      def Incidencia_clean( instance ): 
          #pre save:
          if not instance.deposit:
              instance.amount *= -1 
      
          #business rules:
          errors = {}
      
          #dia i hora sempre informats     
          if not instance.account.enoughCredit: 
              errors.append( 'No enough money.' )
      
          if len( errors ) > 0: 
              raise ValidationError(errors) 
      
      def Issue_pre_save(sender, instance, **kwargs): 
          instance.clean()
      

      这样规则就绑定到模型上,你不需要在模型出现的每个表单上都写代码(here, you can see this on more detail

      【讨论】:

        猜你喜欢
        • 2012-10-25
        • 2012-03-19
        • 1970-01-01
        • 2019-06-20
        • 1970-01-01
        • 2014-06-05
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        相关资源
        最近更新 更多