Django - transactions in the model?

Posted by orokusaki on Stack Overflow See other posts from Stack Overflow or by orokusaki
Published on 2010-03-12T03:59:11Z Indexed on 2010/03/12 4:07 UTC
Read the original article Hit count: 324

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models