首先我们要了解 django 字段类型 SlugField,SlugField 是一个新闻术语(通常叫做短标题)。一个 slug 只能包含字母、数字、下划线或者是连字符,通常用来作为短标签。通常它们是用来放在地址栏的 URL 里的。像 CharField 一样,你可以指定 max_length(也请参阅该部分中的有关数据库可移植性的说明和 max_length)。如果没有指定 max_length, Django 将会默认长度为 50。
我本来是用 pypinyin 在 model save 时自动填充:
最近发现已经有轮子 django-autoslug 干了这事:
Django-autoslug is a reusable Django library that provides an improved slug field which can automatically:
The field is highly configurable.
Python 2.7, 3.5+, or PyPy.
Django 1.7.10 or higher.
It may be possible to successfully use django-autoslug in other environments but they are not tested.
Note
PyPy3 is not officially supported only because there were some problems with permissions and __pycache__ on CI unrelated to django-autoslug itself.
A simple example:
from django.db.models import CharField, Model from autoslug import AutoSlugField class Article(Model): title = CharField(max_length=200) slug = AutoSlugField(populate_from='title')
More complex example:
from django.db.models import CharField, DateField, ForeignKey, Model from django.contrib.auth.models import User from autoslug import AutoSlugField class Article(Model): title = CharField(max_length=200) pub_date = DateField(auto_now_add=True) author = ForeignKey(User) slug = AutoSlugField(populate_from=lambda instance: instance.title, unique_with=['author__name', 'pub_date__month'], slugify=lambda value: value.replace(' ','-'))