Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to name field as 'id' in Django model?

Tags:

python

django

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'?

like image 220
Adogyf Avatar asked May 05 '17 20:05

Adogyf


Video Answer


2 Answers

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.
  • Shadowing a builtin inside a class is less likely to cause confusion than shadowing a builtin inside a function or globally, because class variables are usually prefixed with the name of the class or instance followed by a dot.
  • Having a .id field is idiomatic in Django code, and in fact, Django creates this field by default if you don't do so.
like image 68
Kevin Avatar answered Oct 18 '22 04:10

Kevin


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

like image 7
NS0 Avatar answered Oct 18 '22 05:10

NS0