HorseloverFat
HorseloverFat

Reputation: 3336

django calls validate_unique twice - workaround?

I understand validate_unique is only called when doing a full_clean, which is in turn only called when calling ModelForm.save() - so that means validate_unique won't automatically be called when doing a model_instance.save()

eg. see this answer: https://stackoverflow.com/a/14472335/996792

I do want to call validate_unique when calling model_instance.save so I've overridden my model's save function as follows:

def save(self, *args, **kwargs):
    self.validate_unique()
    super(MyModel, self).save(*args, **kwargs)

However, this produces the following quirk: now when saving from a ModelForm (eg. in the admin), validate_unique is called twice! Presumably once for the ModelForm.save() and once for the Model.save().

Is there anyway round this inefficiency?

I detest unnecessary cruft and this sort of thing bothers me.

Upvotes: 1

Views: 368

Answers (1)

dani herrera
dani herrera

Reputation: 51705

This is a possible workaround:

clean( method is called when request comes from a modelform, set a flag when this method is called:

def clean( self ):
    self.clean_called = True   #<---- this is the flag.
    #other model checks

Overwrite save( i order to call validate_unique only if flag is not set. Don't forget to remove flag.

def save(self, *args, **kwargs):
    flag_is_set = hasattr( self, 'clean_called' ) and self.clean_called
    if not flag_is_set:
        self.validate_unique()
    super(MyModel, self).save(*args, **kwargs)
    self.clean_called = False

Upvotes: 1

Related Questions