2013-12-10 2 views
5

私は2つの外部キーフィールドを持つdjangoモデルを持っています。以下。これらのうちの1つは、各Lcaレコードごとに設定する必要があります。私は、MySQLのトリガと私はこれを行うことができます知っているが、あなたは、モデルのsave方法overrideできジャンゴ2つの外部キーフィールド、ちょうど1つが値に設定され、MySQLデータベースのdjangoモデルのもう1つのヌル

class Lca(models.Model): 
    product    = models.ForeignKey(product, null=True, blank=True) 
    portfolio   = models.ForeignKey(portfolio, null=True, blank=True) 
    carbon_price  = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) 
    name    = models.CharField(max_length=255, blank=True) 
    total_footprint  = models.IntegerField(blank=True, null=True) 
    calculation_type = models.CharField(max_length=9) 
    total_cv   = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) 
    source    = models.CharField(max_length=255, blank=True) 
    date_from   = models.DateField() 
    date_to    = models.DateField(blank=True, null=True) 

    def __unicode__(self): 
     return self.name 
    # end __unicode__ 
# end 

答えて

7

に保存し、これは、条件付きにする方法があった場合、私は思っていた:

def save(self, *args, **kwargs): 
    if self.product and self.portfolio or not self.product and not self.portfolio: 
     raise ValueError('Exactly one of [Lca.product, Lca.portfolio] must be set') 

    super(Lca, self).save(*args, **kwargs) 

注意していますこの方法はbulk_createには適用されません。

+0

ありがとうございました。これは働いている – MagicLAMP

0

追加したいカスタム検証の場合は、モデルclean()を追加することをお勧めします。モデルのクリーンメソッドは、ModelFormsでは自動的に呼び出されますが、save()では呼び出されません。そのため、モデルfull_clean()を自分のメソッドに呼び出し、ValidationErrorsを処理する必要があります。

Model.clean()の詳細については、Django documentationを参照してください。

関連する問題