提问人:ronzenith 提问时间:9/9/2023 更新时间:9/9/2023 访问量:47
Django - 对命名类和参数感到困惑(何时使用大写/复数形式)?
Django - confused about naming class and parameters (when to use uppercase / plural form)?
问:
这种混淆反映了对阶级和框架的不明确理解。
我正在学习 Django 模型中的数据库。我对命名类感到困惑。什么时候使用大写/小写,什么时候使用单数和复数?我用这个例子来关注 freecodecamp 的讲座:
在 中,我分配了一个名为 的类。models.py
Feature(models.Model)
然后,在 中,我为模板分配了功能:views.py
features = def index(request):
Features.objects.all()
return render (request, "index.html", ({"features": features})
在 中,存在一个 for 循环,因此我在 features 中运行 feature 的语法:使用变量和index.html
{{feature.name}}
{{feature.details}}
此时此刻,我只是在决定何时使用功能与功能、功能与功能时不理解地记忆。我发现记住代码相当困难.我需要对命名有一个真正的理解。views.py
下面是一些代码的流程。非常感谢您的帮助。
models.py
class Feature(models.Model):
name = models.CharField(max_length = 100)
details = models.CharField(max_length = 500)
------
settings.py
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
----
admin.py
from .models import Feature
admin.site.register(Feature)
----
views.py
def index(req):
features = Feature.objects.all()
return render(req, "index.html", ({'features': features})
----
index.html
for feature in features:
....{feature.name}
....{feature.details}
答:
按照惯例,Python 中的类是用 PascalCase 指定的,因此它们以大写字母开头。模型通常有一个单数名称,所以 ,而不是 :这是因为单个对象与一个这样的 ,而不是 s 的集合一起工作。Features
Feature
Feature
Feature
Feature
另一方面,变量是用 snake_case 编写的,因此或代替 。如果我们进行如下查询:authorOfBook
feature
features
author_of_book
Feature.objects.all()
结果是对象,所以是集合。虽然集合可以有零个、一个或多个元素。如果我们使用一个事物的集合,我们使用复数,即使该集合只有一个元素,或者根本没有元素。因此,命名它是有道理的:它暗示我们正在处理一系列事物。我们对项目的列表、集合、元组等也这样做。QuerySet
Feature
features
最后,如果我们枚举 ,那么我们将枚举每个项目,这些项目将是一个单独的项目,因此这个名字是单数是有道理的,所以 , 不是 。features
Feature
feature
features
评论
为了扩展公认的答案,所有 python 命名约定都在 PEP8 中定义,您可以在此处阅读:
https://peps.python.org/pep-0008/#prescriptive-naming-conventions
评论