2016-07-08 1 views
1

의 두 모델 이 있습니다. 첫 번째 인스턴스를 저장할 때이 모델의 필드 값을 다른 필드로 보내야합니다.raise_exception을 사용하지 않고 pre_save 신호에 인스턴스를 저장하지 마십시오.

첫 번째 모델 :

class ModelOne(models.Model): 
    # fields... 
    quantity = models.FloatField() 

두 번째 모델 :

class ModelTwo(models.Model): 
    # fields... 
    quantity = models.FloatField() 

pre_save 신호 :

@receiver(pre_save, sender=ModelOne) 
def verify(sender, instance, **kwargs): 
    # Stuff 
    quantity = instance.quantity 
    founded_model_two = ModelTwo.objects.get("""Something""") 
    future_result = founded_model_two.quantity - quantity 
    if future_result < 0: 
     raise Exception("Cannot be less than zero") 

내가 인스턴스를 저장하지 않도록하려면,하지만 난 싶지 않아 예외를 제기하기 위해

답변

0

pre_save의 Exception을 원하지 않는다면 save 방법으로 처리 할 수 ​​있습니다. 왜냐하면 이상적으로 pre_save은 신호를 끝내기 위해 Exception을 던져야하기 때문입니다.

class ModelOne(models.Model): 
    # fields... 
    quantity = models.FloatField() 


    def save(self): 
     if some_condition: 
      super(ModelOne, self).save() 
     else: 
      return #cancel the save if you return no super save object. 

IMHO, 당신은 모든 것을 할 필요가 없습니다하고 데이터를 저장할 필요가 있는지 여부를 확인하기위한 Validators를 사용할 수 있습니다. 데이터를 저장하는 form이있는 경우 양식 유효성 검사를 사용하여 데이터 저장을 중지하십시오.

관련 문제