Permalink
Browse files

Split UpdateInfoBaseModel(): So you can only set "createtime", "lastu…

…pdatetime" or "createby", "lastupdateby" or both types
  • Loading branch information...
1 parent f1e9da5 commit da5edfd46bce541cf738f7684bd0c725f866212a @jedie committed Jul 10, 2012
Showing with 37 additions and 15 deletions.
  1. +37 −15 django_tools/models.py
View
@@ -20,23 +20,35 @@
from django_tools.middlewares import ThreadLocal
-
-
-class UpdateInfoBaseModel(models.Model):
+class UpdateTimeBaseModel(models.Model):
"""
- Base model with update info attributes, used by many models.
- The createby and lastupdateby ForeignKey would be automaticly updated. This needs the
- request object as the first argument in the save method.
-
+ Base model to automatically set:
+ * createtime
+ * lastupdatetime
+
We doesn't used auto_now_add and auto_now here, because they have the odd side effect
see also:
https://github.com/jezdez/django-dbtemplates/commit/2f27327bebe7f2e7b33e5cfb0db517f53a1b9701#commitcomment-1396126
"""
- objects = models.Manager()
-
createtime = models.DateTimeField(default=now, editable=False, help_text="Create time")
lastupdatetime = models.DateTimeField(default=now, editable=False, help_text="Time of the last change.")
+ def save(self, *args, **kwargs):
+ self.lastupdatetime = now()
+ return super(UpdateTimeBaseModel, self).save(*args, **kwargs)
+
+ class Meta:
+ abstract = True
+
+
+class UpdateUserBaseModel(models.Model):
+ """
+ Base model to automatically set:
+ * createby
+ * lastupdateby
+
+ Important: "threadlocals middleware" must be used!
+ """
createby = models.ForeignKey(User, editable=False, related_name="%(class)s_createby",
null=True, blank=True, # <- If the model used outsite a real request (e.g. unittest, db shell)
help_text="User how create this entry.")
@@ -45,20 +57,30 @@ class UpdateInfoBaseModel(models.Model):
help_text="User as last edit this entry.")
def save(self, *args, **kwargs):
- """
- Automatic update createby and lastupdateby attributes with the request object witch must be
- the first argument.
- """
- self.lastupdatetime = now()
current_user = ThreadLocal.get_current_user()
if current_user and isinstance(current_user, User):
if self.pk == None or kwargs.get("force_insert", False): # New model entry
self.createby = current_user
self.lastupdateby = current_user
- return super(UpdateInfoBaseModel, self).save(*args, **kwargs)
+ return super(UpdateUserBaseModel, self).save(*args, **kwargs)
+
+ class Meta:
+ abstract = True
+
+class UpdateInfoBaseModel(UpdateTimeBaseModel, UpdateUserBaseModel):
+ """
+ Base model to automatically set:
+ * createtime
+ * lastupdatetime
+ and:
+ * createby
+ * lastupdateby
+
+ Important: "threadlocals middleware" must be used!
+ """
class Meta:
abstract = True

0 comments on commit da5edfd

Please sign in to comment.