python - Altering unique fields of inherited Django model -
in django, i'm trying create base model can used track different version of other model's data in transparent way. 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 create separate records, # don't delete mark deleted, etc. pass class somedata(warehouse): id = models.integerfield( primary_key=true ) name = models.charfield(unique=true)
the problem have somedata.name
not unique, tuple ('version_number', 'name' )
is.
i know can use meta
class in somedata
unique_together
wondering whether done in more transparent way. is, dynamically modifying/creating unique_together
field.
final note: maybe handling model inheritance not correct approach looked pretty appealing me if can handle field uniqueness problem.
edit: word 'dynamic' in context misleading. want uniqueness preserved @ database level. idea have different version of data.
a give here small example above model (assuming abstract model inheritance, in same table):
the database contain:
version_number | id | name | #comment 0 | 1 | bob | first insert 0 | 2 | nicky | first insert 1 | 1 | bobby | bob changed name on day x.y.z 0 | 3 | malcom| first insert 1 | 3 | malco | name change 2 | 3 | momo | again...
and custom model manager filter data (taking max on version number every unique id) that: somedata.objects.all() return
id | name 1 | bobby 2 | nicky 3 | momo
and offer others method can return data in version n-1.
obviously use timestamp instead of version number can retrieve data @ given date principle remains same.
now problem when ./manage.py makemigrations models above, enforce uniqueness on somedata.name , on somedata.id when need uniqueness on ('somedata.id','version_number') , ('somedata.name', 'version_number'). explicitly, need append fields base models fields of inherited models declared unique in db , times manage.py command run and/or production server runs.
by "dynamically modifying/creating unique_together
field", assume mean want enforce @ code level, not @ database level.
you can in save()
method of 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 helps!
Comments
Post a Comment