Django - transactions in the model?
- by orokusaki
Models (disregard typos / minor syntax issues. It's just pseudo-code):
class SecretModel(models.Model):
some_unique_field = models.CharField(max_length=25, unique=True) # Notice this is unique.
class MyModel(models.Model):
secret_model = models.OneToOneField(SecretModel, editable=False) # Not in the form
spam = models.CharField(max_length=15)
foo = models.IntegerField()
def clean(self):
SecretModel.objects.create(some_unique_field=self.spam)
Now if I go do this:
MyModel.objects.create(spam='john', foo='OOPS') # Obviously foo won't take "OOPS" as it's an IntegerField.
#.... ERROR HERE
MyModel.objects.create(spam='john', foo=5) # So I try again here.
#... IntegrityError because SecretModel with some_unique_field = 'john'
already exists.
I understand that I could put this into a view with a request transaction around it, but I want this to work in the Admin, and via an API, etc. Not just with forms, or views. How is it possible?