0

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?

loar
  • 1,505
  • 1
  • 15
  • 34
  • you can using [`pre_save`](https://docs.djangoproject.com/en/1.10/ref/signals/#pre-save), eg is like this answer http://stackoverflow.com/a/6462188/6396981 – binpy Mar 02 '17 at 11:44
  • @SancaKembang how would that help ? The OP is asking how to get his model instance within the `clean` method. – bruno desthuilliers Mar 02 '17 at 11:49

1 Answers1

1

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.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118