简体   繁体   中英

Duplicated models with Django admin

For a specific model I use Django admin interface. I implemented custom validation (clean methods) and save method.

So, I have something like this:

class DailyActivitiesAdmin(admin.ModelAdmin):
form= MyCustomFormForm

    def save_model(self, request, obj, form, change):
     .... my custom save ....

class MyCustomFormForm(forms.ModelForm):

    ....
    def clean(self):
      ... my custom validation ...

    def clean_my_field(self):
      ... my custom field validation ...

My question is:

Have I to manage explicitly the transaction from validation to save model or the atomicity is already managed in Django admin?

A my customer reported me a bug about it:

Into my clean validation I implemented a check to avoid similar models; Sometime he can create model duplicated. I think that probably he make more click on save button and probably he had a slowly internet connection.

It is a possible scenario? Can I void it? For example, Can I disable the save buttons during the save requests?

Can I guarantee atomicity in some way if it is not already managed?

PS: I use Python 3, Djnago 2 and Postgres

You have to block rows for updates explicitly. Use transaction.atomic() and select_for_update() . Here is an example:

@transaction.atomic
def update_bank_account():
    # Another call to update_bank_account will block until the first one is finished
    account = BankAccount.objects.select_for_update().get(id=123)
    sleep(120)
    account.usd += 100
    account.save()

Docs:

Into my clean validation I implemented a check to avoid similar models; Sometime he can create model duplicated.

This sounds like an issue I had. Make sure save() isn't being called from within your clean function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM