I was trying to design a model in django with some auditing fields. Such as created at, created by, updated at and updated by. Those four columns are going to be repeated across all my models in different applications.
My first question, is there a way to put those columns and can include them in my class each time i need them?
My second question, what is the point of the related_name attribute in the below code? without it the code will return an error, plus the value must be unique across the entire app. Is there a way to ensure its always unique?
class Poll(models.Model):
question=models.CharField(max_length=300)
start_poll_at=models.DateTimeField(null=True)
end_poll_at=models.DateTimeField(null=True)
is_active=models.BooleanField(default=True)
created_at=models.DateField("Created at")
created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by")
updated_at=models.DateTimeField("Updated at")
updated_by=models.ForeignKey(User, db_column="updated_by", null=True, related_name="poll_user_updated_by")
class Choice(models.Model):
choice=models.CharField(max_length=200)
created_at=models.DateField("Created at")
created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by")
updated_at=models.DateTimeField("Updated at")
updated_by=models.ForeignKey(User, db_column="updated_by", null=True, related_name="poll_user_updated_by")
Thanks
Try this:
class AbstractClass(models.Model):
created_at=models.DateField("Created at")
created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by")
updated_at=models.DateTimeField("Updated at")
updated_by=models.ForeignKey(User, db_column="updated_by", null=True, related_name="poll_user_updated_by")
class Meta:
abstract = True
And then use it as base for other models:
class Poll(AbstractClass):
question=models.CharField(max_length=300)
start_poll_at=models.DateTimeField(null=True)
end_poll_at=models.DateTimeField(null=True)
is_active=models.BooleanField(default=True)
This is the django documentation about this: http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With