9đź‘Ť
âś…
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.
👤Kevin
7đź‘Ť
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)
👤NS0
- Deploying Django (fastcgi, apache mod_wsgi, uwsgi, gunicorn)
- Using custom methods in filter with django-rest-framework
Source:stackexchange.com