命名作为 python 保留名称的 django 模型字段的正确习惯用法是什么?

发布于 2024-08-04 23:34:59 字数 196 浏览 3 评论 0原文

我有一个模型,需要有一个名为 complex 的字段和另一个名为 type 的字段。这些都是 python 保留名称。根据 PEP 8,我应该分别将它们命名为 complex_type_,但 django 不允许我使用以下划线命名的字段。处理这个问题的正确方法是什么?

I have a model that needs to have a field named complex and another one named type. Those are both python reserved names. According to PEP 8, I should name them complex_ and type_ respectively, but django won't allow me to have fields named with a trailing underscore. Whats the proper way to handle this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森末i 2024-08-11 23:34:59

这些例子都没有问题。只需使用complextype即可。您仅在非常有限的范围内进行跟踪(类定义本身)。之后,您将使用点表示法 (self.type) 访问它们,因此不会有歧义:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
...     type = 'abc'
... 
>>> f = Foo()
>>> f.type
'abc'
>>> class Bar(object):
...     complex = 123+4j
... 
>>> bar = Bar()
>>> bar.complex
(123+4j)
>>> 

There's no problem with those examples. Just use complex and type. You are only shadowing in a very limited scope (the class definition itself). After that, you'll be accessing them using dot notation (self.type), so there's no ambiguity:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
...     type = 'abc'
... 
>>> f = Foo()
>>> f.type
'abc'
>>> class Bar(object):
...     complex = 123+4j
... 
>>> bar = Bar()
>>> bar.complex
(123+4j)
>>> 
绿光 2024-08-11 23:34:59

您真的想使用db_column="complex" 参数并将您的字段命名为其他名称吗?

Do you really want to use the db_column="complex" argument and call your field something else?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文