class MyModel(models.Model):
id = models.IntegerField(primary_key=True)
or
class MyModel(models.Model):
id_ = models.IntegerField(primary_key=True)
According to pep8 single_trailing_underscore_ should be used by to avoid conflicts with Python keyword but having column named id_ would look ugly and possibly cause confusion to someone not familiar with python on database level.
Django docs use 'id' column name: https://docs.djangoproject.com/en/1.11/ref/models/fields/#uuidfield.
Is it safe to name this field as 'id'?
Python allows shadowing builtins in any context. Builtins are at the lowest precedence in the LEGB model (local variables, enclosing scopes, global variables, builtins). At the same time, code in other modules will not be affected by this shadowing; id
will still refer to the builtin in other contexts. So it's entirely safe to shadow builtins. The "real" question is whether it's a Good Idea. In this case:
id()
is one of the less-commonly used builtins..id
field is idiomatic in Django code, and in fact, Django creates this field by default if you don't do so.Yes, it's fine to use id
if you are adding a custom primary key for a Django model, just like in the example you linked to in the docs. For regular usage however, Django automatically creates an id
field that is defined as
id = models.AutoField(primary_key=True)
Read more here
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