Django模型字段包含奇怪的属性_("private") [英] Django model field contain strange attribute _("private")

查看:46
本文介绍了Django模型字段包含奇怪的属性_("private")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我一直在学习Django,在阅读时,遇到了以下我不理解的代码块.

Currently I have been learning Django and while reading, I have come across the below code block which I don't understand.

private = models.BooleanField(
        _('private'),
        default=False,
        help_text=_('theme is available ONLY for the site.'),
    )

上面的代码行包含 _('private'),我无法理解它的作用.我知道将 _ 用于翻译相关的内容.为什么没有为 _((private))声明属性名称?

The above line of code contains _('private') and I am not able to understand what it does. I know about using _ for translation-related stuff. Why attribute name not declared for _("private")?

我试图在线找到答案,但是无法.

I have tried to find the answer online but have been unable.

谢谢.

推荐答案

如您在

As you can see in the source code of Django, the constructor of a Field (which BooleanField inherits) takes verbose_name as first positional argument. So, your first argument (_('private')) will be affected to verbose_name.

但是,为了使您的代码更清晰,我建议将其作为关键字参数传递:

However, to make your code clearer, I would recommend to pass it as a keyword argument:

private = models.BooleanField(
    verbose_name=_('private'),
    default=False,
    help_text=_('theme is available ONLY for the site.'),
)

使用 verbose_name 的关键字参数将使您和阅读您的代码的人更加清楚,尤其是因为

Using keyword argument for verbose_name will make it clearer for you and people reading your code, especially since Django documentation does not give the order of positional arguments. Using positional argument forces readers to read Django source code to know what it is.

使用关键字参数时,可以根据需要放置参数,因此此代码将相同:

When you use keyword arguments, you can position your arguments as you like, so this code will work the same:

private = models.BooleanField(
    help_text=_('theme is available ONLY for the site.'),
    verbose_name=_('private'),
    default=False,
)

这篇关于Django模型字段包含奇怪的属性_("private")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆