django - Django FieldType 默认字符串参数的用途
问题描述
在Django 2.0 Mozilla 教程中,他们有时在将各种 fieldTypes 定义为新模型的一部分时使用初始字符串参数。例如,他们使用以下代码段中的作者变量 (ForeignKey FieldType) 和 isbn (CharField) 来执行此操作。
class Book(models.Model):
"""
Model representing a book (but not a specific copy of a book).
"""
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
# Foreign Key used because book can only have one author, but authors can have multiple books
# Author as a string rather than object because it hasn't been declared yet in the file.
summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book')
isbn = models.CharField('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
这个字符串的目的是什么?我查看了Django 模型文档,找不到作为选项的初始字符串参数。我假设它是用于数据库中列的值,但它是使用可选参数db_column指定的。任何见解都值得赞赏。谢谢。
解决方案
当我们查看这两个类的源代码(更具体地说,它们的__init__()
方法)时,(ForeignKey
和CharField
)我们可以找到类似下面的内容
ForeignKey
class ForeignKey(ForeignObject):
....
....
def __init__(self, to, on_delete=None, related_name=None, related_query_name=None,
limit_choices_to=None, parent_link=False, to_field=None,
db_constraint=True, **kwargs):
# code
# code
CharField
这个类是inherited from
Field类,所以
class Field(RegisterLookupMixin):
...
...
... code
def __init__(self, verbose_name=None, name=None, primary_key=False,
max_length=None, unique=False, blank=False, null=False,
db_index=False, rel=None, default=NOT_PROVIDED, editable=True,
serialize=True, unique_for_date=None, unique_for_month=None,
unique_for_year=None, choices=None, help_text='', db_column=None,
db_tablespace=None, auto_created=False, validators=(),
error_messages=None):
# code
# code
结论
类的第一个参数在两个类中是不同的。CharField
将verbose_name
其作为第一个参数,而ForeignKey
将to
raled 模型名称作为第一个参数
资源
CharField
源代码Field
源代码ForeignKey
源代码
希望这可以消除您的疑问:)
推荐阅读
- ios - 如何使用 Core Motion 将 uiview 从一个点移动到另一个点
- mysql - Codeigniter SQL 查询不适用于 WHERE 子句中的特殊字符
- django - 在服务器中找不到 URL
- ssl-certificate - Bot Emulator V4 连接:对 https://localhost:44378/api/messages 的请求失败,原因:无法验证第一个证书
- go - 执行外部命令并返回其输出
- java - sqlite 中的 checkIfRowExists() 不起作用
- asp.net-core-mvc - ASP.NET Core MVC 在局部视图/ViewComponent 中提交表单
- c++ - 在代码块 (C++) 中调试时,我可以选择跳过所有打开的内部库调用和函数吗?
- python - 三元图作为子图
- git - 如何使用 git diff 作为 difftool?