loar
loar

Reputation: 1765

How to get the instance of the model in clean()

I've overwritten the clean() method to perform a custom validation in my model. Is there any way to get the instance of the model that is being saved?

class Consumption(models.Model):
    storage = models.ForeignKey(Storage, related_name='consumption')
    timestamp = UnixDateTimeField()
    consumption = models.BigIntegerField(help_text='Consumption in Bytes')

    def clean(self):
        if self.storage_type == PRIMARY:
            if Storage.objects.filter(company=self.company, storage_type=PRIMARY).exists():
                raise ValidationError({'storage_type': 'Already exists a Primary storage'})

When I modify an Storage, which is related to a consumption, it raises the ValidationError. So I'd like to improve the filter like this:

Storage.objects.exclude(pk=self.instance.pk).filter(...)

Where can I take the instance from?

Upvotes: 0

Views: 1332

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

As usual in all python instancemethods, the current instance is the first positional parameter, canonically named self:

class MyModel(models.Model):
    # fields etc here

    def clean(self):
       print("current instance is {}".format(self))

EDIT:

Since you clarified the question, it seems that what you want is the current instance's related storage, not the Consumption instance itself (which is self). And quite simply, since the current instance is self, the related storage instance is self.storage.

Upvotes: 1

Related Questions