Reputation: 165
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'?
Upvotes: 13
Views: 5026
Reputation: 30151
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.Upvotes: 9
Reputation: 6096
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)
Upvotes: 7