Altering unique fields of inherited Django model

Home / Uncategorized / Altering unique fields of inherited Django model

Question:
In Django, I’m trying to create a base model that can be used to track the different version of some other model’s data in a transparent way. Something like:class Warehouse(models.Model):
version_number = models.IntegerField()
objects = CustomModelManagerFilteringOnVersionNumber()

class Meta_abstract=True

def save(self, *args, **kwargs):# handling here version number incrementation
# never overwrite data but create separate records,
# don’t delete but mark as deleted, etc.
pass

class SomeData(Warehouse):name = models.CharField(unique=True)

The problem I have is that SomeData.name is actually not unique, the tuple (‘version_number’, ‘name’ ) is.

I know I can use the Meta class in SomeData with unique_together but I was wondering whether this could be done in a more transparent way. That is, dynamically modifying/creating this unique_together field.

Final note: maybe handling this with model inheritance is not the correct approach but it looked pretty appealing to me if I can handle this field uniqueness problem.


Answer:
By "dynamically modifying/creating this unique_together field", I assume you mean you want to enforce this at the code level, not at the database level.

You can do it in the save() method of your model:from django.core.exceptions import ValidationError

def save(self, *args, **kwargs):if SomeData.objects.filter(name=self.name, version_number=self.version_number).exclude(pk=self.pk).exists():raise ValidationError(‘Such thing exists’)

return super(SomeData, self).save(*args, **kwargs)

Hope it helps!
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *