标签归档:django-models

在Django中,“子弹”是什么?

问题:在Django中,“子弹”是什么?

当我阅读Django代码时,我经常在模型中看到所谓的“子弹”。我不太清楚这是什么,但是我知道它与URL有关。应该如何以及何时使用这种this子?

(我已经在本词汇表中阅读了其定义。)

When I read Django code I often see in models what is called a “slug”. I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used?

(I have read its definition in this glossary.)


回答 0

“子弹”是一种通常使用已获得的数据生成有效URL的方法。例如,a使用文章标题来生成URL。我建议通过给定标题(或另一段数据)的函数来生成段,而不要手动设置它。

一个例子:

<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>

现在,我们假设我们有一个Django模型,例如:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

您将如何使用URL和有意义的名称引用该对象?例如,您可以使用Article.id,因此URL如下所示:

www.example.com/article/23

或者,您可能希望像这样引用标题:

www.example.com/article/The 46 Year Old Virgin

由于网址中的空格无效,因此必须将其替换为%20,这将导致:

www.example.com/article/The%2046%20Year%20Old%20Virgin

两次尝试都不会产生非常有意义且易于阅读的URL。这个更好:

www.example.com/article/the-46-year-old-virgin

在此示例中,the-46-year-old-virgin是一个子弹:它是通过将所有字母缩进小写并用连字符替换空格来从标题创建的-

另请参见此网页的URL。

A “slug” is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

An example:

<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>

Now let’s pretend that we have a Django model such as:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:

www.example.com/article/23

Or, you might want to reference the title like this:

www.example.com/article/The 46 Year Old Virgin

Since spaces aren’t valid in URLs, they must be replaced by %20, which results in:

www.example.com/article/The%2046%20Year%20Old%20Virgin

Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:

www.example.com/article/the-46-year-old-virgin

In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -.

Also see the URL of this very web page for another example.


回答 1

如果我可以提供一些历史背景:

术语“弹头”与铸造金属铅,在这种情况下,外面的新闻字体被做事情。然后,每张纸的字体工厂都会定期重新熔化,并用新鲜的模具重新铸造,因为经过多次印刷后,它们已经磨损了。像我这样的学徒从那里开始了他们的职业生涯,并一路攀升到了顶峰(不再有)。

排版者必须以倒排的方式撰写文章文字,并以明智的方式堆叠主角。因此,在打印时,字母将直接在纸上。所有的印刷机都能像打印的报纸一样快地阅读报纸。因此,(如蜗牛)和慢故事(最后一个要修复的故事)在板凳上等待着很多,只能通过拳头字母来识别,大部分标题通常更易读。一些“热门”新闻在板凳上等待着,可能在最后组装和确定印刷之前进行最后一分钟的更正(晚上用纸)。

Django来自堪萨斯州《劳伦斯》杂志的办公室。也许还有一些印刷术语仍然存在。django爱好者和来自法国的友好的老-男孩。

If I may provide some historical context :

The term “slug” has to do with casting metal—lead, in this case—out of which the press fonts were made. Every paper then had its fonts factory regularly re-melted and recast in fresh molds, since after many prints they became worn out. Apprentices like me started their career there, and went all the way to the top (not anymore).

Typographs had to compose the text of an article in a backward manner with lead characters stacked in a wise. So at printing time the letters would be straight on the paper. All typographs could read the newspaper mirrored as fast as the printed one. Therefore the slugs, (like snails) also the slow stories (the last to be fixed) were many on the bench waiting, solely identified by their fist letters, mostly the whole title generally more readable. Some “hot” news were waiting there on the bench, for possible last minute correction, (Evening paper) before last assembly and definitive printing.

Django emerged from the offices of the Lawrence journal in Kansas. Where probably some printing jargon still lingers. A-django-enthusiast-&-friendly-old-slug-boy-from-France.


回答 2

“子弹”一词来自报纸生产的世界。

这是制作过程中故事的非正式名称。随着故事的发展,从节拍记者(假设这些故事甚至还存在吗?)一直到编辑器再到“印刷机”,这就是它所引用的名称,例如,“您是否已修复了’凯特和威廉的故事?”。

某些系统(例如Django)使用slug作为URL的一部分来定位故事,例如www.mysite.com/archives/kate-and-william

甚至Stack Overflow本身也可以使用GEB-ish (a)自引用进行此操作/programming/427102/what-is-a-slug-in-django/427201#427201,尽管您可以将其替换为blahblah,但仍然可以。

它可能甚至早于该日期,因为编剧在每个场景的开始处都有“条形线”,这基本上设置了该场景的背景(位置,时间等)。这非常相似,是随后内容的序言或序言。

在Linotype机器上,子弹是由单个字母形式创建的单线金属片。通过为整个行制作一个块,这大大改善了旧的逐字符合成。

尽管以下是纯粹的推测,但“鼻涕虫”的早期含义是使用伪造的硬币(必须以某种方式加以按压)。我可以设想将用法转换为印刷术语(因为必须使用原始字符压制嵌条),然后从“金属片”定义更改为“故事摘要”定义。从那里开始,从正确的打印到在线世界仅一步之遥。


(a)道格拉斯·霍夫施塔特Douglas Hofstadter )的作品《巴赫·戈德尔·埃舍尔》(Godel Escher,Bach),我(至少)认为这是伟大的现代知识分子作品之一。您还应该查看他的其他作品“ Metamagical Themas”。

The term ‘slug’ comes from the world of newspaper production.

It’s an informal name given to a story during the production process. As the story winds its path from the beat reporter (assuming these even exist any more?) through to editor through to the “printing presses”, this is the name it is referenced by, e.g., “Have you fixed those errors in the ‘kate-and-william’ story?”.

Some systems (such as Django) use the slug as part of the URL to locate the story, an example being www.mysite.com/archives/kate-and-william.

Even Stack Overflow itself does this, with the GEB-ish(a) self-referential https://stackoverflow.com/questions/427102/what-is-a-slug-in-django/427201#427201, although you can replace the slug with blahblah and it will still find it okay.

It may even date back earlier than that, since screenplays had “slug lines” at the start of each scene, which basically sets the background for that scene (where, when, and so on). It’s very similar in that it’s a precis or preamble of what follows.

On a Linotype machine, a slug was a single line piece of metal which was created from the individual letter forms. By making a single slug for the whole line, this greatly improved on the old character-by-character compositing.

Although the following is pure conjecture, an early meaning of slug was for a counterfeit coin (which would have to be pressed somehow). I could envisage that usage being transformed to the printing term (since the slug had to be pressed using the original characters) and from there, changing from the ‘piece of metal’ definition to the ‘story summary’ definition. From there, it’s a short step from proper printing to the online world.


(a) “Godel Escher, Bach”, by one Douglas Hofstadter, which I (at least) consider one of the great modern intellectual works. You should also check out his other work, “Metamagical Themas”.


回答 3

Slug是一个报纸术语。子弹是某事物的简短标签,仅包含字母,数字,下划线或连字符。它们通常在URL中使用。(如Django文档)

Django中的Slug字段用于为动态创建的网页存储和生成有效的URL

就像您在Stack Overflow上添加此问题的方式一样,并生成了一个动态页面,当您在地址栏中看到时,您会看到问题标题带有“-”代替空格。这正是田的工作。

您输入的标题是这样的->在Django中,“子弹”是什么?

将其存储到slug字段中后,它变成“ what-is-a-slug-in-django”(请参阅​​此页面的URL)

Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. (as in Django docs)

A slug field in Django is used to store and generate valid URLs for your dynamically created web pages.

Just like the way you added this question on Stack Overflow and a dynamic page was generated and when you see in the address bar you will see your question title with “-” in place of the spaces. That’s exactly the job of a slug field.

The title entered by you was something like this -> What is a “slug” in Django?

On storing it into a slug field it becomes “what-is-a-slug-in-django” (see URL of this page)


回答 4

这里

“ Slug”是报纸上的术语,但此处的含义是URL的最后一部分。例如,标题为“关于Django的一点”的帖子将自动变为“ bit-about-django”(当然,如果您不喜欢自动生成的子弹,则可以轻松地对其进行更改)。

From here.

“Slug” is a newspaper term, but what it means here is the final bit of the URL. For example, a post with the title, “A bit about Django” would become, “bit-about-django” automatically (you can, of course, change it easily if you don’t like the auto-generated slug).


回答 5

它是URL的描述性部分,可以使它更具人工描述性,但不一定是Web服务器所必需的- 在Django中,“子弹”是什么?slug是“ in-django-what-is-a-slug”,但是不使用slug来确定所服务页面(至少在此站点上)

It’s a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server – in What is a “slug” in Django? the slug is ‘in-django-what-is-a-slug’, but the slug is not used to determine the page served (on this site at least)


回答 6

Slug是特定内容的URL友好短标签。它仅包含字母,数字,下划线或连字符。子弹通常与各自的内容一起保存,并作为URL字符串传递。

Slug可以使用SlugField创建

例如:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)

如果您想使用标题作为标题,django有一个简单的函数称为 slugify

from django.template.defaultfilters import slugify

class Article(models.Model):
    title = models.CharField(max_length=100)

    def slug(self):
        return slugify(self.title)

如果需要唯一性,请添加unique=True子弹字段。

例如,从前面的示例中:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

您是否懒于进行处理?不用担心,此插件将为您提供帮助。 django-autoslug

Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.

Slug can create using SlugField

Ex:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)

If you want to use title as slug, django has a simple function called slugify

from django.template.defaultfilters import slugify

class Article(models.Model):
    title = models.CharField(max_length=100)

    def slug(self):
        return slugify(self.title)

If it needs uniqueness, add unique=True in slug field.

for instance, from the previous example:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

Are you lazy to do slug process ? don’t worry, this plugin will help you. django-autoslug


回答 7

也可以在django-admin上自动启动。在ModelAdmin上添加:

prepopulated_fields = {'slug': ('title', )}

如这里:

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug')
    search_fields = ('content', )

    prepopulated_fields = {'slug': ('title', )}

Also auto slug at django-admin. Added at ModelAdmin:

prepopulated_fields = {'slug': ('title', )}

As here:

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug')
    search_fields = ('content', )

    prepopulated_fields = {'slug': ('title', )}

回答 8

ug

某物的简短标签,仅包含字母,数字,下划线或连字符。它们通常在URL中使用。例如,在典型的博客条目URL中:

https://www.djangoproject.com/weblog/2008/apr/12/spring/ 最后一点(弹簧)是弹头。

slug

A short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. For example, in a typical blog entry URL:

https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit (spring) is the slug.


在django中区分null = True,空白= True

问题:在django中区分null = True,空白= True

当我们在Django中添加数据库字段时,通常会这样写:

models.CharField(max_length=100, null=True, blank=True)

同样是与做ForeignKeyDecimalField等有什么根本区别在其

  1. null=True 只要
  2. blank=True 只要
  3. null=Trueblank=True

在相对于不同的(CharFieldForeignKeyManyToManyFieldDateTimeField)字段。使用1/2/3有哪些优点/缺点?

When we add a database field in django we generally write:

models.CharField(max_length=100, null=True, blank=True)

The same is done with ForeignKey, DecimalField etc. What is the basic difference in having

  1. null=True only
  2. blank=True only
  3. null=True, blank=True

in respect to different (CharField, ForeignKey, ManyToManyField, DateTimeField) fields. What are the advantages/disadvantages of using 1/2/3?


回答 0

null=True在数据库的列中设置NULL(与相对NOT NULL)。Django字段类型(例如DateTimeField或)的空白值ForeignKey将存储NULL在数据库中。

blank确定是否需要表单中的字段。这包括管理员和您的自定义表单。如果blank=True是,则不需要该字段,如果是,则False该字段不能为空。

两者的组合是如此频繁,因为通常如果您要允许表单中的字段为空白,则还需要数据库来允许NULL该字段的值。CharFields和TextFields 是一个exceptions,在Django中永远不会另存为NULL。空值作为空字符串('')存储在DB中。

一些例子:

models.DateTimeField(blank=True) # raises IntegrityError if blank

models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form

显然,这两个选项在使用上没有逻辑意义(尽管null=True, blank=False如果您希望始终以表单形式要求字段,则可能会有用例,当通过诸如Shell之类的对象处理对象时,这是可选的。)

models.CharField(blank=True) # No problem, blank is stored as ''

models.CharField(null=True) # NULL allowed, but will never be set as NULL

CHARTEXT类型永远不会NULL被Django 保存,因此null=True没有必要。但是,您可以手动设置这些字段之一None以强制将其设置为NULL。如果您有可能需要这样做的情况,则仍应包括null=True

null=True sets NULL (versus NOT NULL) on the column in your DB. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the DB.

blank determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True then the field will not be required, whereas if it’s False the field cannot be blank.

The combo of the two is so frequent because typically if you’re going to allow a field to be blank in your form, you’re going to also need your database to allow NULL values for that field. The exception is CharFields and TextFields, which in Django are never saved as NULL. Blank values are stored in the DB as an empty string ('').

A few examples:

models.DateTimeField(blank=True) # raises IntegrityError if blank

models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form

Obviously, Those two options don’t make logical sense to use (though there might be a use case for null=True, blank=False if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)

models.CharField(blank=True) # No problem, blank is stored as ''

models.CharField(null=True) # NULL allowed, but will never be set as NULL

CHAR and TEXT types are never saved as NULL by Django, so null=True is unnecessary. However, you can manually set one of these fields to None to force set it as NULL. If you have a scenario where that might be necessary, you should still include null=True.


回答 1

这是Django 1.8 的ORM映射blanknull字段的方式

class Test(models.Model):
    charNull        = models.CharField(max_length=10, null=True)
    charBlank       = models.CharField(max_length=10, blank=True)
    charNullBlank   = models.CharField(max_length=10, null=True, blank=True)

    intNull         = models.IntegerField(null=True)
    intBlank        = models.IntegerField(blank=True)
    intNullBlank    = models.IntegerField(null=True, blank=True)

    dateNull        = models.DateTimeField(null=True)
    dateBlank       = models.DateTimeField(blank=True)
    dateNullBlank   = models.DateTimeField(null=True, blank=True)        

PostgreSQL 9.4创建的数据库字段是:

CREATE TABLE Test (
  id              serial                    NOT NULL,

  "charNull"      character varying(10),
  "charBlank"     character varying(10)     NOT NULL,
  "charNullBlank" character varying(10),

  "intNull"       integer,
  "intBlank"      integer                   NOT NULL,
  "intNullBlank"  integer,

  "dateNull"      timestamp with time zone,
  "dateBlank"     timestamp with time zone  NOT NULL,
  "dateNullBlank" timestamp with time zone,
  CONSTRAINT Test_pkey PRIMARY KEY (id)
)

MySQL 5.6创建的数据库字段是:

CREATE TABLE Test (
     `id`            INT(11)     NOT  NULL    AUTO_INCREMENT,

     `charNull`      VARCHAR(10) NULL DEFAULT NULL,
     `charBlank`     VARCHAR(10) NOT  NULL,
     `charNullBlank` VARCHAR(10) NULL DEFAULT NULL,

     `intNull`       INT(11)     NULL DEFAULT NULL,
     `intBlank`      INT(11)     NOT  NULL,
     `intNullBlank`  INT(11)     NULL DEFAULT NULL,

     `dateNull`      DATETIME    NULL DEFAULT NULL,
     `dateBlank`     DATETIME    NOT  NULL,
     `dateNullBlank` DATETIME    NULL DEFAULT NULL
)

This is how the ORM maps blank & null fields for Django 1.8

class Test(models.Model):
    charNull        = models.CharField(max_length=10, null=True)
    charBlank       = models.CharField(max_length=10, blank=True)
    charNullBlank   = models.CharField(max_length=10, null=True, blank=True)

    intNull         = models.IntegerField(null=True)
    intBlank        = models.IntegerField(blank=True)
    intNullBlank    = models.IntegerField(null=True, blank=True)

    dateNull        = models.DateTimeField(null=True)
    dateBlank       = models.DateTimeField(blank=True)
    dateNullBlank   = models.DateTimeField(null=True, blank=True)        

The database fields created for PostgreSQL 9.4 are :

CREATE TABLE Test (
  id              serial                    NOT NULL,

  "charNull"      character varying(10),
  "charBlank"     character varying(10)     NOT NULL,
  "charNullBlank" character varying(10),

  "intNull"       integer,
  "intBlank"      integer                   NOT NULL,
  "intNullBlank"  integer,

  "dateNull"      timestamp with time zone,
  "dateBlank"     timestamp with time zone  NOT NULL,
  "dateNullBlank" timestamp with time zone,
  CONSTRAINT Test_pkey PRIMARY KEY (id)
)

The database fields created for MySQL 5.6 are :

CREATE TABLE Test (
     `id`            INT(11)     NOT  NULL    AUTO_INCREMENT,

     `charNull`      VARCHAR(10) NULL DEFAULT NULL,
     `charBlank`     VARCHAR(10) NOT  NULL,
     `charNullBlank` VARCHAR(10) NULL DEFAULT NULL,

     `intNull`       INT(11)     NULL DEFAULT NULL,
     `intBlank`      INT(11)     NOT  NULL,
     `intNullBlank`  INT(11)     NULL DEFAULT NULL,

     `dateNull`      DATETIME    NULL DEFAULT NULL,
     `dateBlank`     DATETIME    NOT  NULL,
     `dateNullBlank` DATETIME    NULL DEFAULT NULL
)

回答 2

如Django模型字段参考中所述:链接

栏位选项

以下参数可用于所有字段类型。所有都是可选的。


null

Field.null

如果为True,则Django将NULL在数据库中存储空值。默认值为False

避免null在基于字符串的字段(例如CharField和)上使用, TextField因为空字符串值将始终存储为空字符串,而不是NULL。如果基于字符串的字段具有null=True,则表示它具有两个“无数据”的可能值:NULL和空字符串。在大多数情况下,为“无数据”设置两个可能的值是多余的。Django约定是使用空字符串,而不是 NULL

对于基于字符串的字段和基于非字符串的字段,blank=True如果您希望允许表单中的空值,还需要进行设置,因为该null参数仅影响数据库存储(请参阅参考资料blank)。

注意

使用Oracle数据库后端时,无论此属性如何,都将存储值NULL表示空字符串


blank

Field.blank

如果为True,则该字段允许为空白。默认值为False

请注意,这与有所不同nullnull与数据库完全相关,而blank与验证相关。如果字段包含blank=True,则表单验证将允许输入一个空值。如果字段包含blank=False,则将需要该字段。

As said in Django Model Field reference: Link

Field options

The following arguments are available to all field types. All are optional.


null

Field.null

If True, Django will store empty values as NULL in the database. Default is False.

Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data”; the Django convention is to use the empty string, not NULL.

For both string-based and non-string-based fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).

Note

When using the Oracle database backend, the value NULL will be stored to denote the empty string regardless of this attribute


blank

Field.blank

If True, the field is allowed to be blank. Default is False.

Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.


回答 3

理解Django模型字段定义中的选项至少有两个作用是至关重要的:定义数据库表,定义默认格式和验证模型形式。(我之所以说“默认值”,是因为可以始终通过提供自定义表单来覆盖这些值。)某些选项影响数据库,某些选项影响表单,而某些选项同时影响这两种形式。

关于nullblank,其他答案已经明确表明,前者影响数据库表定义,而后者影响模型验证。我认为,通过查看所有四种可能配置的用例,可以使区分更加清楚:

  • null=Falseblank=False:这是默认的配置和手段,该值在所有情况下需要。

  • null=Trueblank=True:表示该字段在所有情况下都是可选的。(但是,如下所述,这不是使基于字符串的字段为可选的推荐方法。)

  • null=Falseblank=True:表示表单不需要值,但是数据库需要。有许多用例:

    • 最常见的用法是用于基于字符串的可选字段。如文档中所述,Django习惯用法是使用空字符串表示缺少的值。如果NULL还允许,您将最终以两种不同的方式指示缺失值。

    • 另一种常见情况是,您想根据另一个字段的值自动计算一个字段(例如,使用您的save()方法)。您不希望用户以某种形式提供值(因此blank=True),但是您希望数据库强制始终提供值(null=False)。

    • 另一个用途是当您想要指示a ManyToManyField是可选的时。因为此字段是作为单独的表而不是数据库列实现的,null所以没有意义blank不过,的值仍会影响表单,控制在没有关系时验证是否成功。

  • null=Trueblank=False:表示表单需要一个值,但数据库不需要。这可能是最不常用的配置,但是有一些用例:

    • 要求用户始终包含一个值是完全合理的,即使您的业务逻辑实际上并不需要它也是如此。毕竟,表单只是添加和编辑数据的一种方式。您可能拥有的代码生成的数据不需要与人工编辑器一样严格的验证。

    • 我看到的另一个用例是当你有一个ForeignKey你不想允许级联删除的情况。也就是说,在正常使用中,该关系应始终存在(blank=False),但是如果它指向的对象恰好被删除,则您也不想删除该对象。在这种情况下,您可以使用null=Trueon_delete=models.SET_NULL实现一种简单的软删除

It’s crucial to understand that the options in a Django model field definition serve (at least) two purposes: defining the database tables, and defining the default format and validation of model forms. (I say “default” because the values can always be overridden by providing a custom form.) Some options affect the database, some options affect forms, and some affect both.

When it comes to null and blank, other answers have already made clear that the former affects the database table definition and the latter affects model validation. I think the distinction can be made even clearer by looking at use cases for all four possible configurations:

  • null=False, blank=False: This is the default configuration and means that the value is required in all circumstances.

  • null=True, blank=True: This means that the field is optional in all circumstances. (As noted below, though, this is not the recommended way to make string-based fields optional.)

  • null=False, blank=True: This means that the form doesn’t require a value but the database does. There are a number of use cases for this:

    • The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If NULL was also allowed you would end up with two different ways to indicate a missing value.

    • Another common situation is that you want to calculate one field automatically based on the value of another (in your save() method, say). You don’t want the user to provide the value in a form (hence blank=True), but you do want the database to enforce that a value is always provided (null=False).

    • Another use is when you want to indicate that a ManyToManyField is optional. Because this field is implemented as a separate table rather than a database column, null is meaningless. The value of blank will still affect forms, though, controlling whether or not validation will succeed when there are no relations.

  • null=True, blank=False: This means that the form requires a value but the database doesn’t. This may be the most infrequently used configuration, but there are some use cases for it:

    • It’s perfectly reasonable to require your users to always include a value even if it’s not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data which doesn’t need the same stringent validation that you want to require of a human editor.

    • Another use case that I’ve seen is when you have a ForeignKey for which you don’t wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False), but if the thing it points to happens to be deleted, you don’t want this object to be deleted too. In that case you can use null=True and on_delete=models.SET_NULL to implement a simple kind of soft deletion.


回答 4

您可能有答案,但是直到今天,仍然很难判断是否将null = True或blank = True或两者都放在一个字段中。我个人认为为开发人员提供这么多的选择是非常无用的,而且令人困惑。让句柄根据需要为空或空格。

我遵循这张表,来自Django的两个独家新闻

You may have your answer however till this day it’s difficult to judge whether to put null=True or blank=True or both to a field. I personally think it’s pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.

I follow this table, from Two Scoops of Django:


回答 5

简单null=True定义数据库应该接受NULL值,另一方面,blank=True在表单验证中定义此字段是否应该接受空白值(如果blank=True它接受该字段中没有值的表单,并且blank=False在表单验证中为[默认值],它将显示此字段为必填错误。

null=True/False 与数据库有关

blank=True/False 与表单验证有关

Simply null=True defines database should accept NULL values, on other hand blank=True defines on form validation this field should accept blank values or not(If blank=True it accept form without a value in that field and blank=False[default value] on form validation it will show This field is required error.

null=True/False related to database

blank=True/False related to form validation


回答 6

这是带有blank= True和的字段的示例null=True

description = models.TextField(blank = True,null = True)

在这种情况下:: blank = True告诉我们的表格可以将描述字段留空

null = True:告诉我们的数据库可以在db字段中记录一个空值并且不给出错误。

Here is an example of the field with blank= True and null=True

description = models.TextField(blank=True, null= True)

In this case: blank = True: tells our form that it is ok to leave the description field blank

and

null = True: tells our database that it is ok to record a null value in our db field and not give an error.


回答 7

这里,是的主要区别null=Trueblank=True

两者的默认值nullblank值为False。这两个值都在字段级别起作用,即我们是否要保留字段nullblank

null=True将字段的值设置为NULL即无数据。它基本上是针对数据库列的值。

date = models.DateTimeField(null=True)

blank=True确定是否需要表单中的字段。这包括管理员和您自己的自定义表单。

title = models.CharField(blank=True) // title can be kept blank. 在数据库("")中将被存储。 null=True blank=True这意味着该字段在所有情况下都是可选的。

epic = models.ForeignKey(null=True, blank=True)
// The exception is CharFields() and TextFields(), which in Django are never saved as NULL. Blank values a

Here, is the main difference of null=True and blank=True:

The default value of both null and blank is False. Both of these values work at field level i.e., whether we want to keep a field null or blank.

null=True will set the field’s value to NULL i.e., no data. It is basically for the databases column value.

date = models.DateTimeField(null=True)

blank=True determines whether the field will be required in forms. This includes the admin and your own custom forms.

title = models.CharField(blank=True) // title can be kept blank. In the database ("") will be stored. null=True blank=True This means that the field is optional in all circumstances.

epic = models.ForeignKey(null=True, blank=True)
// The exception is CharFields() and TextFields(), which in Django are never saved as NULL. Blank values a

回答 8

null = True

意味着对于要填充的字段没有数据库的约束,因此您可以拥有一个具有空值的对象,该对象具有此选项。

blank = True

意味着没有django形式的验证约束。因此,当您modelForm为此模型填写时,可以不填写此选项。

null = True

Means there is no constraint of database for the field to be filled, so you can have an object with null value for the filled that has this option.

blank = True

Means there is no constraint of validation in django forms. so when you fill a modelForm for this model you can leave field with this option unfilled.


回答 9

null和blank的默认值为False。

空:与数据库有关。定义给定的数据库列是否将接受空值。

空白:与验证相关。调用form.is_valid()时,将在表单验证期间使用它。

话虽这么说,具有null = True和blank = False的字段是完全可以的。在数据库级别上,该字段可以为NULL,但是在应用程序级别上,它是必填字段。

现在,大多数开发人员都将其弄错了:为基于字符串的字段(如CharField和TextField)定义null = True。避免这样做。否则,您最终将获得两个可能的“无数据”值,即:和空字符串。为“无数据”设置两个可能的值是多余的。Django约定是使用空字符串,而不是NULL。

The default values of null and blank are False.

Null: It is database-related. Defines if a given database column will accept null values or not.

Blank: It is validation-related. It will be used during forms validation, when calling form.is_valid().

That being said, it is perfectly fine to have a field with null=True and blank=False. Meaning on the database level the field can be NULL, but in the application level it is a required field.

Now, where most developers get it wrong: Defining null=True for string-based fields such as CharField and TextField. Avoid doing that. Otherwise, you will end up having two possible values for “no data”, that is: None and an empty string. Having two possible values for “no data” is redundant. The Django convention is to use the empty string, not NULL.


回答 10

当我们在Django admin中保存任何内容时,将在Django级别和数据库级别进行两步验证。我们无法在数字字段中保存文本。

数据库的数据类型为NULL,没什么。当Django在数据库中创建列时,它指定它们不能为空。而且,如果您尝试保存NULL,则会出现数据库错误。

同样在Django-Admin级别,默认情况下所有字段都是必填字段,您无法保存空白字段,Django会抛出错误。

因此,如果要保存空白字段,则需要在Django和数据库级别允许它。blank = True-将允许管理面板中的空字段null = True-将允许将NULL保存到数据库列。

When we save anything in Django admin two steps validation happens, on Django level and on Database level. We can’t save text in a number field.

Database has data type NULL, it’s nothing. When Django creates columns in the database it specifies that they can’t be empty. And if you will try to save NULL you will get the database error.

Also on Django-Admin level, all fields are required by default, you can’t save blank field, Django will throw you an error.

So, if you want to save blank field you need to allow it on Django and Database level. blank=True – will allow empty field in admin panel null=True – will allow saving NULL to the database column.


回答 11

有一点null=True甚至在CharField或上也有必要TextField,那就是数据库unique为列设置了标志。

换句话说,如果您在Django中具有唯一的Char / TextField,则需要使用以下代码:

models.CharField(blank=True, null=True, unique=True)

对于非唯一的CharField或TextField,最好跳过null=True一些,否则某些字段将被设置为NULL,而另一些字段将被设置为“”,并且您每次都必须检查字段值是否为NULL。

There’s one point where null=True would be necessary even on a CharField or TextField and that is when the database has the unique flag set for the column.

In other words, if you’ve a unique Char/TextField in Django, you’ll need to use this:

models.CharField(blank=True, null=True, unique=True)

For non-unique CharField or TextField, you’ll be better off skipping the null=True otherwise some fields will get set as NULL while others as “” , and you’ll have to check the field value for NULL everytime.


回答 12

是数据库和空白是字段的验证要显示在文本框一样的用户界面得到的人的姓氏。如果lastname = models.charfield(blank = true),则没有要求用户输入姓氏,因为这是可选字段。如果lastname = models.charfield(null = true), 则意味着如果该字段未从用户那里获取任何值,则它将作为空字符串“”存储在数据库中。

null is for database and blank is for fields validation that you want to show on user interface like textfield to get the last name of person. If lastname=models.charfield (blank=true) it didnot ask user to enter last name as this is the optional field now. If lastname=models.charfield (null=true) then it means that if this field doesnot get any value from user then it will store in database as an empty string ” “.


回答 13

模型中null = True和blank = True的含义还取决于如何在表单类中定义这些字段。

假设您定义了以下类:

class Client (models.Model):
    name = models.CharField (max_length=100, blank=True)
    address = models.CharField (max_length=100, blank=False)

如果表单类的定义如下:

class ClientForm (ModelForm):
    class Meta:
        model = Client
        fields = ['name', 'address']
        widgets = {
            'name': forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
            'address': forms.TextInput (attrs = {'class': 'form-control form-control-sm'})
        }

然后,“名称”字段将不是强制性的(由于模型中的blank = True),而“地址”字段将是强制性的(由于模型中的blank = False)。

但是,如果已经这样定义ClientForm类:

class ClientForm (ModelForm):
    class Meta:
        model = Client
        fields = ['name', 'address']

    name = forms.CharField (
        widget = forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
    )
    address = forms.CharField (
        widget = forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
    )

然后,两个字段(“名称”和“地址”)都是必填字段“因为以声明方式定义的字段保持原样”https://docs.djangoproject.com/zh/3.0/topics/forms/modelforms/) ,即表单字段的’required’属性的默认值为True,即使在模型中将该字段设置为blank = True,这也将要求填写字段’name’和’address’。

The meaning of null=True and blank=True in the model also depends on how these fields were defined in the form class.

Suppose you have defined the following class:

class Client (models.Model):
    name = models.CharField (max_length=100, blank=True)
    address = models.CharField (max_length=100, blank=False)

If the form class has been defined like this:

class ClientForm (ModelForm):
    class Meta:
        model = Client
        fields = ['name', 'address']
        widgets = {
            'name': forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
            'address': forms.TextInput (attrs = {'class': 'form-control form-control-sm'})
        }

Then, the ‘name’ field will not be mandatory (due to the blank=True in the model) and the ‘address’ field will be mandatory (due to the blank=False in the model).

However, if the ClientForm class has been defined like this:

class ClientForm (ModelForm):
    class Meta:
        model = Client
        fields = ['name', 'address']

    name = forms.CharField (
        widget = forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
    )
    address = forms.CharField (
        widget = forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
    )

Then, both fields (‘name’ and ‘address’) will be mandatory, “since fields defined declaratively are left as-is” (https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/), i.e. the default for the ‘required’ attribute of the form field is True and this will require that the fields ‘name’ and ‘address’ are filled, even if, in the model, the field has been set to blank=True.


回答 14

null-如果为True,则默认为False,Django将在数据库中将null存储为null。

空白-如果为true,则默认值为False,该字段允许为空白

更多,请转到 https://docs.djangoproject.com/en/3.0/topics/db/models/

null – default is False if True, Django will store empty as null in the database.

blank – default is False if true that field is allowed to be blank

more, goto https://docs.djangoproject.com/en/3.0/topics/db/models/


回答 15

下表说明了主要区别:

+--------------------------------------------------------------------+
| Purpose                  | null=True        | blank = True         |
|--------------------------|------------------|----------------------|
| Field can be empty in DB | Do this          | Unaffected           |
|--------------------------|------------------|----------------------|
| ModelForm(required field)| Unaffected       | field not required   |
|--------------------------|------------------|----------------------|
| Form Validation          | Unaffected       | field not required   |
|--------------------------|------------------|----------------------|
| on_delete=SET_NULL       | Need this        | Unaffected           |
+--------------------------------------------------------------------+

This table below demonstrates the main differences:

+--------------------------------------------------------------------+
| Purpose                  | null=True        | blank = True         |
|--------------------------|------------------|----------------------|
| Field can be empty in DB | Do this          | Unaffected           |
|--------------------------|------------------|----------------------|
| ModelForm(required field)| Unaffected       | field not required   |
|--------------------------|------------------|----------------------|
| Form Validation          | Unaffected       | field not required   |
|--------------------------|------------------|----------------------|
| on_delete=SET_NULL       | Need this        | Unaffected           |
+--------------------------------------------------------------------+

回答 16

在很简单的话

空白不同于空值。

纯粹数据库相关的,而空白是验证相关的(在形式所需)

如果是null=True,Django会的store empty values as NULL in the database。如果有一个字段blank=True,则将进行表单验证allow entry of an empty value。如果字段的空白为False,则将需要该字段。

In Very simple words,

Blank is different than null.

null is purely database-related, whereas blank is validation-related(required in form).

If null=True, Django will store empty values as NULL in the database. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.


如何在Django queryset过滤中执行不等于?

问题:如何在Django queryset过滤中执行不等于?

在Django模型QuerySets中,我看到比较值存在__gt__lt,但是存在__ne// !=/ <>不等于?)。

我想使用不等于过滤掉:

例:

Model:
    bool a;
    int x;

我想要

results = Model.objects.exclude(a=true, x!=5)

!=不正确的语法。我试过__ne<>

我最终使用:

results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5)

In Django model QuerySets, I see that there is a __gt and __lt for comparitive values, but is there a __ne/!=/<> (not equals?)

I want to filter out using a not equals:

Example:

Model:
    bool a;
    int x;

I want

results = Model.objects.exclude(a=true, x!=5)

The != is not correct syntax. I tried __ne, <>.

I ended up using:

results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5)

回答 0

也许Q对象可以解决这个问题。我从未使用过它们,但似乎可以将它们取反并组合起来,就像普通的python表达式一样。

更新:我只是尝试了一下,它似乎工作得很好:

>>> from myapp.models import Entry
>>> from django.db.models import Q

>>> Entry.objects.filter(~Q(id = 3))

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]

Maybe Q objects could be of help for this problem. I’ve never used them but it seems they can be negated and combined much like normal python expressions.

Update: I Just tried it out, it seems to work pretty well:

>>> from myapp.models import Entry
>>> from django.db.models import Q

>>> Entry.objects.filter(~Q(id = 3))

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]

回答 1

您的查询似乎有一个双重否定,您想排除x不为5的所有行,换句话说,您想包括x为5的所有行。我相信这可以解决问题。

results = Model.objects.filter(x=5).exclude(a=true)

要回答您的特定问题,不存在“不等于”的问题,但这可能是因为django同时提供了“过滤器”和“排除”方法,因此您始终可以切换逻辑回合以获得所需的结果。

Your query appears to have a double negative, you want to exclude all rows where x is not 5, so in other words you want to include all rows where x IS 5. I believe this will do the trick.

results = Model.objects.filter(x=5).exclude(a=true)

To answer your specific question, there is no “not equal to” but that’s probably because django has both “filter” and “exclude” methods available so you can always just switch the logic round to get the desired result.


回答 2

field=value查询中的语法是的简写field__exact=value。也就是说,Django将查询运算符放在标识符中的查询字段上。Django支持以下运算符:

exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range
year
month
day
week_day
isnull
search
regex
iregex

我敢肯定,如Dave Vogt所建议的那样,将它们与Q对象结合使用,filter()或者exclude()Jason Baker所建议的那样使用,您将获得几乎所有可能查询所需的确切信息。

the field=value syntax in queries is a shorthand for field__exact=value. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:

exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range
year
month
day
week_day
isnull
search
regex
iregex

I’m sure by combining these with the Q objects as Dave Vogt suggests and using filter() or exclude() as Jason Baker suggests you’ll get exactly what you need for just about any possible query.


回答 3

使用Django 1.7创建自定义查找很容易。Django官方文档中有一个__ne查找示例。

您需要先创建查找本身:

from django.db.models import Lookup

class NotEqual(Lookup):
    lookup_name = 'ne'

    def as_sql(self, qn, connection):
        lhs, lhs_params = self.process_lhs(qn, connection)
        rhs, rhs_params = self.process_rhs(qn, connection)
        params = lhs_params + rhs_params
        return '%s <> %s' % (lhs, rhs), params

然后,您需要注册:

from django.db.models.fields import Field
Field.register_lookup(NotEqual)

现在,您可以__ne像下面这样在查询中使用查找:

results = Model.objects.exclude(a=True, x__ne=5)

It’s easy to create a custom lookup with Django 1.7. There’s an __ne lookup example in Django official documentation.

You need to create the lookup itself first:

from django.db.models import Lookup

class NotEqual(Lookup):
    lookup_name = 'ne'

    def as_sql(self, qn, connection):
        lhs, lhs_params = self.process_lhs(qn, connection)
        rhs, rhs_params = self.process_rhs(qn, connection)
        params = lhs_params + rhs_params
        return '%s <> %s' % (lhs, rhs), params

Then you need to register it:

from django.db.models.fields import Field
Field.register_lookup(NotEqual)

And now you can use the __ne lookup in your queries like this:

results = Model.objects.exclude(a=True, x__ne=5)

回答 4

Django 1.9 / 1.10中,有三个选项。

  1. excludefilter

    results = Model.objects.exclude(a=true).filter(x=5)
  2. 使用Q()对象~运算符

    from django.db.models import Q
    object_list = QuerySet.filter(~Q(a=True), x=5)
  3. 注册自定义查找功能

    from django.db.models import Lookup
    from django.db.models.fields import Field
    
    @Field.register_lookup
    class NotEqual(Lookup):
        lookup_name = 'ne'
    
        def as_sql(self, compiler, connection):
            lhs, lhs_params = self.process_lhs(compiler, connection)
            rhs, rhs_params = self.process_rhs(compiler, connection)
            params = lhs_params + rhs_params
            return '%s <> %s' % (lhs, rhs), params

    register_lookup在加装饰的Django 1.8和启用自定义查找和往常一样:

    results = Model.objects.exclude(a=True, x__ne=5)

In Django 1.9/1.10 there are three options.

  1. Chain exclude and filter

    results = Model.objects.exclude(a=true).filter(x=5)
    
  2. Use Q() objects and the ~ operator

    from django.db.models import Q
    object_list = QuerySet.filter(~Q(a=True), x=5)
    
  3. Register a custom lookup function

    from django.db.models import Lookup
    from django.db.models.fields import Field
    
    @Field.register_lookup
    class NotEqual(Lookup):
        lookup_name = 'ne'
    
        def as_sql(self, compiler, connection):
            lhs, lhs_params = self.process_lhs(compiler, connection)
            rhs, rhs_params = self.process_rhs(compiler, connection)
            params = lhs_params + rhs_params
            return '%s <> %s' % (lhs, rhs), params
    

    The register_lookup decorator was added in Django 1.8 and enables custom lookup as usual:

    results = Model.objects.exclude(a=True, x__ne=5)
    

回答 5

虽然与模型,您可以用过滤=__gt__gte__lt__lte,你不能使用ne!=或者<>。但是,使用Q对象可以实现更好的过滤。

您可以避免链接QuerySet.filter()QuerySet.exlude(),并使用以下代码:

from django.db.models import Q
object_list = QuerySet.filter(~Q(field='not wanted'), field='wanted')

While with the Models, you can filter with =, __gt, __gte, __lt, __lte, you cannot use ne, != or <>. However, you can achieve better filtering on using the Q object.

You can avoid chaining QuerySet.filter() and QuerySet.exlude(), and use this:

from django.db.models import Q
object_list = QuerySet.filter(~Q(field='not wanted'), field='wanted')

回答 6

等待设计决策。同时,使用exclude()

Django问题追踪器具有引人注目的条目#5763,标题为“ Queryset没有“不相等”的过滤运算符”。值得注意的是,(截至2016年4月)它是​​“在9年前开放”(在Django石器时代),“在4年前关闭”和“在5个月前最后一次更改”。

通读讨论,这很有趣。基本上,一些人认为__ne应增加也有人说exclude()是清晰的,因此__ne 应该添加。

(我同意前者,因为后者的论点大致相当于说Python不应该拥有!===,因为它已经拥有not了……)

Pending design decision. Meanwhile, use exclude()

The Django issue tracker has the remarkable entry #5763, titled “Queryset doesn’t have a “not equal” filter operator”. It is remarkable because (as of April 2016) it was “opened 9 years ago” (in the Django stone age), “closed 4 years ago”, and “last changed 5 months ago”.

Read through the discussion, it is interesting. Basically, some people argue __ne should be added while others say exclude() is clearer and hence __ne should not be added.

(I agree with the former, because the latter argument is roughly equivalent to saying Python should not have != because it has == and not already…)


回答 7

使用排除和过滤

results = Model.objects.filter(x=5).exclude(a=true)

Using exclude and filter

results = Model.objects.filter(x=5).exclude(a=true)

回答 8

您应该使用filterexclude喜欢这个

results = Model.objects.exclude(a=true).filter(x=5)

You should use filter and exclude like this

results = Model.objects.exclude(a=true).filter(x=5)

回答 9

代码的最后一位将排除x!= 5并且a为True的所有对象。尝试这个:

results = Model.objects.filter(a=False, x=5)

请记住,上一行中的=符号将False赋给参数a,并将数字5赋给参数x。它不是在检查是否相等。因此,实际上没有任何方法可以在查询调用中使用!=符号。

The last bit of code will exclude all objects where x!=5 and a is True. Try this:

results = Model.objects.filter(a=False, x=5)

Remember, the = sign in the above line is assigning False to the parameter a and the number 5 to the parameter x. It’s not checking for equality. Thus, there isn’t really any way to use the != symbol in a query call.


回答 10

结果= Model.objects.filter(a = True).exclude(x = 5)
生成此sql:
从tablex中选择*,其中a = 0且x!= 5
sql取决于您的True / False字段的表示方式以及数据库引擎。Django代码是您所需要的。

results = Model.objects.filter(a = True).exclude(x = 5)
Generetes this sql:
select * from tablex where a != 0 and x !=5
The sql depends on how your True/False field is represented, and the database engine. The django code is all you need though.

回答 11

Django-model-values(公开:作者)提供了NotEqual查找的实现,如此答案所示。它还为此提供了语法支持:

from model_values import F
Model.objects.exclude(F.x != 5, a=True)

Django-model-values (disclosure: author) provides an implementation of the NotEqual lookup, as in this answer. It also provides syntactic support for it:

from model_values import F
Model.objects.exclude(F.x != 5, a=True)

回答 12

您要查找的所有具有a=false 或的 对象x=5。在Django中,|充当查询集OR之间的运算符:

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)

What you are looking for are all objects that have either a=false or x=5. In Django, | serves as OR operator between querysets:

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)

回答 13

这将给您想要的结果。

from django.db.models import Q
results = Model.objects.exclude(Q(a=True) & ~Q(x=5))

对于不相等,可以~在相等查询上使用。显然,Q可以用来达到相等的查询。

This will give your desired result.

from django.db.models import Q
results = Model.objects.exclude(Q(a=True) & ~Q(x=5))

for not equal you can use ~ on an equal query. obviously, Q can be used to reach the equal query.


回答 14

注意此问题的许多错误答案!

Gerard的逻辑是正确的,尽管它将返回一个列表而不是一个查询集(这可能无关紧要)。

如果需要查询集,请使用Q:

from django.db.models import Q
results = Model.objects.filter(Q(a=false) | Q(x=5))

Watch out for lots of incorrect answers to this question!

Gerard’s logic is correct, though it will return a list rather than a queryset (which might not matter).

If you need a queryset, use Q:

from django.db.models import Q
results = Model.objects.filter(Q(a=false) | Q(x=5))