简体   繁体   中英

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

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.
  • 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM