Django naming conventions for dates
Is there any naming convention for "created"开发者_运维问答 and "last edit" dates in Django?
ie. in Symfony Framework this fields are named by default:
- created_at
- updated_at
Indeed, as far as I can tell there's no canonical convention for Django, but I really like the Rails convention (which I suppose also inspired Symphony):
created_at
for DateTime fieldscreated_on
for Date fields
created
works fine for creation dates, but as soon as you have more ambiguous fields like activated
, it becomes a problem. Is it a boolean or a date/datetime? Naming conventions exist to help developers understand code faster and waste less time with unimportant decisions. That's the philosophy behind the Convention over Configuration paradigm, which is big in the Rails community but not as much in Django's unfortunately. This confusion I mentioned for example is typical and that's why I prefer to always be extra clear:
- If it's a boolean
is_activated
- If it's datetime
activated_at
- If it's just a date
activated_on
I've heard people say that "you shouldn't mix field names with data types" but it seems like a rather empty tip in my opinion and I've never heard any concrete argument behind it. If we want to optimize code readability and decision making then I really think explicit naming conventions are the way to go.
In Django origin models this fields are named based on Model type ie.
- auth.User: date_joined
- comments.Comment: submit_date
So probably we should follow this convention.
I don't think there's something like a canonical way of naming such things in Django. Some parts are well covered by PEP8, mostly because this sort of thing is out of scope of Django, since it's much more a matter of style (and maybe house conventions).
That said, I think it's pretty common to name these fields as created_at
and updated_at
, and I personally follow this convention when writing my own code. I advise to avoid names like created
or updated
since they're ambiguous (although some popular libs use that style): are they booleans or something else? is_created
/is_updated
, if you need those, are better options.
I prefer created
and updated
without the _at
suffix. I don't know of any "canonical" preference for naming the fields.
For what it is worth, I think Rails uses created_at / created_on
and updated_at / updated_on
.
Django Model Utils has a model mixin for this, naming them created
and modified
-- I recommend using their model mixin to easily standardize across of your models and projects.
精彩评论