Good way for a Revision Controllled Model? - Django
here is my attempt:
Example #1
class RevisionControlledValue(models.Model):
created = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User)
value = models.TextField()
class Meta:
ordering = ('-created', )
class DjangoPony(models.Model):
names = models.ManyToManyField(RevisionControlledValue, \
related_name="fromname_djangopony_set")
colors = models.ManyToManyField(RevisionControlledValue, \
related_name="fromcolor_djangopony_set")
@property
def name(self):
return self.names.latest('created')
Example #2
class RevisionControlledValue(models.Model):
created = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
value = models.TextField()
class Meta:
ordering = ('-created', )
class DjangoPony(models.Model):
@property
def name(self):
return self.revisioncontr开发者_Python百科olledvalue.latest('created')
Both feel a bit iffy to me, especially the content_type one, which I would think should be favorable option.
With the content_type one, there is no knowledge within the model of the different types of revision controlled fields and what if I want different types of fields?
For the first one Many to Many does not really match the logic, as it is a One to Many relationship.
Any tips or ideas? :)
There is app for that django-reversion. If you really only want to have reversion control on one field break it off into its own table and make a 1-to-1 relationship.
I think you forgot the word fields in your title. =) I guess I would use an approach that leaves the original model intact. Something starting with:
class DjangoPony(models.Model):
name = models.TextField()
color = models.TextField()
class RevisionControlledValue(models.Model):
created = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User)
value = models.TextField()
field = models.CharField(max_length=20)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
This assumes you'll only be using it for TextFields. To make it really beautiful, you could create a new field, let's say ReversionTextField
that automatically creates the reversion object when the model is saved.
@Jason
You don't need to create new models... from the reversion docs:
Saving a subset of fields If you only want a subset of fields to be saved to a revision, you can specify a fields argument to the register method.
reversion.register(YourModel, fields=["pk", "foo", "bar"])
Reversion is pretty well tested and the low level api lets you do pretty much all I've ever wanted.
精彩评论