Django 模型命名约定

发布于 2024-07-10 07:14:23 字数 28 浏览 8 评论 0原文

Django 模型类的首选命名约定是什么?

What is the preferred naming convention for Django model classes?

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

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

发布评论

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

评论(4

楠木可依 2024-07-17 07:14:23

Django 模型只是 Python 类,因此 Python 命名约定详见 PEP-8 申请。

例如:

  1. Person
  2. Category
  3. ZipCode

如果 Django 在创建相应的表时无法正确实现类名的复数形式,您可以通过在内部 META 类中设置自定义 verbose_name_plural 字段来轻松覆盖复数形式。 例如:

class Story(models.Model):
    ...

    class Meta:
        verbose_name_plural = "stories"

Django models are just Python classes, so the Python naming conventions detailed in PEP-8 apply.

For example:

  1. Person
  2. Category
  3. ZipCode

If Django fails to pluralize the class name properly when creating the corresponding table, you can easily override the pluralization by setting a custom verbose_name_plural field in an inner META class. For example:

class Story(models.Model):
    ...

    class Meta:
        verbose_name_plural = "stories"
坏尐絯℡ 2024-07-17 07:14:23

据我所知,这个想法是类名应该是单数并且应该使用不带空格的SentenceCase。 所以你会有这样的名字:

Person
TelephoneNumber

然后 Django 管理工具知道如何将它们复数。 对于像这样的名称来说效果不太好:

Category

它被复数化为类别,但是我们走了...

除此之外,只需给它一个对您有意义的名称,并简洁地总结该类要代表的内容。

As far as I know, the idea is that the class name should be singular and should use SentenceCase with no spaces. So you'd have names like:

Person
TelephoneNumber

Then the Django admin tool knows how to pluralise them. Doesn't work so nicely for names like:

Category

which gets pluralised as Categorys, but there we go...

Apart from that, just give it a name that means something to you and succinctly sums up what the class is meant to represent.

Ben

清眉祭 2024-07-17 07:14:23

在大多数编程语言中,人们更喜欢为对象/模型赋予单一名称,因为这些模型也由数据库系统中的表表示。 极简主义每次都是一个不错的选择,可以避免将来出现一些意义冲突。

举例说明;
https://stackoverflow.com/a/5841297/2643226

In most of programming languages, people prefer give a singular names to the objects/models because these models are also represented by tables in your database system. The minimalism is a good choice everytime to avoid some meaning conflicts in the future.

To exemplify;
https://stackoverflow.com/a/5841297/2643226

花间憩 2024-07-17 07:14:23

另外,当需要多个单词的 Model 关联对象时,可以使用 _set 属性。 示例:

class ProcessRoom(models.Model):
...
    plant = models.ForeignKey("Plant", verbose_name='planta', on_delete=models.CASCADE)

那么,相关对象将是:

plant = Plant.object.get(id=1)
process_rooms = plant.processroom_set.all

In adition, when you need related objects for a Model of more than one word, you can use the _set attribute. Example:

class ProcessRoom(models.Model):
...
    plant = models.ForeignKey("Plant", verbose_name='planta', on_delete=models.CASCADE)

Then, related objects will be:

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