I want to use a base model which will ensure a created_at
and _updated_at
timestamp on all my records, however I don’t want the names to clash with other models fields, is it accepted to use leading underscores in the names or will it clash with queryset querying?
class BaseModel(models.Model):
_created_at = models.DateTimeField(auto_now_add=True, db_index=True, editable=False)
_modified_at = models.DateTimeField(auto_now=True, db_index=True, editable=False)
objects = BaseManager()
class Meta:
abstract = True
I found my answer,
In the docs it is stated
- A field name cannot end with an underscore, for similar reasons.
Trying to see why the docs only recommends against trailing and not leading I came across this SO post, based on which it seems like it shouldn’t be a problem to use leading underscores.
Superficially, I don’t see any problem with that. A single underscore doesn’t create a problem as a leading character in a filter
for example. And a related reference is going to show through as a two underscores followed by the underscored name.
However, I will point out that using a leading underscore does not prevent a name conflict with classes inheriting from your abstract model. There is nothing preventing the subordinate classes from reusing those names.
Thanks for your answer, indeed I know it won’t prevent explicit clashes, but my thought is that to prepend an underscore will be done with extra thought, while just putting fields don’t always follow the hierarchy of the model