title: Django model calls an API before save
body: <p>I have a Django model that needs to call an external API just before saving. The API call is irreversible so I want to call it only before the DB save happens.</p>
  <p>My code looks something like this:</p>
  <pre class="lang-py prettyprint-override"><code>class Model1(models.Model):
      some_string = models.CharField(max_length=100)
  
  class Model2(models.Model):
      model1 = models.OneToOneField(Model1, on_delete=models.CASCADE)
      num1 = models.IntegerField()
      num2 = models.IntegerField()
      api_output = models.models.JSONField()
  
      def save(self, *args, **kwargs):
          self.api_output = API.call_method(self.num1, self.num2, self.model1.some_string)
          super().save(*args, **kwargs)
  </code></pre>
  <p><code>Model2</code> objects can be created from Django Admin but also from the code using <code>Model2.objects.create()</code>.</p>
  <p>I have 2 questions:</p>
  <ol>
  <li><p>When creating an instance of <code>Model2</code> from Django Admin - if the API call fails (throws an exception) I'd like Django Admin to show a human-readable error instead of the 5xx error page. One way to do that is to have a <code>clean()</code> method but I don't want to call the API before the object is actually saved. Also, when using <code>Model2.objects.create()</code> the <code>clean()</code> method is not called. Is there a way to call the API inside <code>save()</code> and still have Django Admin print a nice error if the call fails?</p>
  </li>
  <li><p>I noticed that during <code>save()</code>, if the <code>OneToOneField</code> constraint is violated (for example trying to create 2 instances of <code>Model2</code> with the same instance of <code>Model1</code>), the validation happens after the API call which means the API is being called although the object is not valid. Is there a way to perform all validations before my code runs (which call the API)?</p>
  </li>
  </ol>