首页 > 解决方案 > 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指定的。任何见解都值得赞赏。谢谢。

标签: django

解决方案


当我们查看这两个类的源代码(更具体地说,它们的__init__()方法)时,(ForeignKeyCharField)我们可以找到类似下面的内容

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


结论
类的第一个参数在两个类中是不同的。CharFieldverbose_name其作为第一个参数,而ForeignKeytoraled 模型名称作为第一个参数

资源

  1. CharField源代码
  2. Field源代码
  3. ForeignKey源代码

    希望这可以消除您的疑问:)

推荐阅读