unique_for_date parameter for SlugField


First, I am reading a book on django and from it have created the following models.py (entire models.py included at the end, the two fields related to the question are here): 
slug = models.SlugField(max_length = 250,
unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus we can retrieve single posts using date and slug
publish = models.DateTimeField(default = timezone.now)

无论如何,我一直在网上搜索,看到您可以在创建DateTimeField()时使用unique_for_date参数,但是当涉及到在SlugField()中使用该参数时,我发现大约十年前在这里提出了一个问题(如何在 Django 中创建unique_for_field slug?(,所以认为问这个问题不会有什么坏处。如果可以做到这一点,有人可以解释该参数在做什么吗?这也许在 django 中已经过时了吗?提前谢谢。

models.py:

# Create your models here.
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Pusblished'),
)
title = models.CharField(max_length = 250)
slug = models.SlugField(max_length = 250,
unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus we can retrieve single posts using date and slug
author = models.ForeignKey(User,
on_delete= models.CASCADE,
related_name= 'blog_posts'
)
body = models.TextField()
publish = models.DateTimeField(default = timezone.now)
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length = 10,
choices = STATUS_CHOICES,
default = 'draft')

指的是Django文档,其中陈述如下: Field.unique_for_date¶ 将其设置为日期字段或日期时间字段的名称,以要求此字段对于日期字段的值是唯一的。

例如,如果你有一个字段标题有 unique_for_date="pub_date",那么 Django 将不允许输入两个具有相同标题和pub_date的记录。

请注意,如果将其设置为指向日期时间字段,则仅考虑该字段的日期部分。此外,当USE_TZ为 True 时,将在保存对象时的当前时区执行检查。

这由 Model.validate_unique(( 在模型验证期间强制执行,但不是在数据库级别强制执行。如果任何unique_for_date约束涉及不属于 ModelForm 的字段(例如,如果其中一个字段列在排除中或具有 editable=False(,Model.validate_unique(( 将跳过对该特定约束的验证。

https://docs.djangoproject.com/en/3.0/ref/models/fields/#unique-for-date

您可以将其视为unique_together在这种情况下,您无法在同一天使用相同的 slug 保存相同的帖子

例: 如果您在 3 年 6 月 2020 日并且您的 slug 是 Hello 如果您尝试在同一天再次编写名为 Hello 的相同 slug,它将被拒绝,但如果您在其他日期编写相同的 slug,它将被接受

最新更新