首先我们要了解 django 字段类型 SlugField,SlugField 是一个新闻术语(通常叫做短标题)。一个 slug 只能包含字母、数字、下划线或者是连字符,通常用来作为短标签。通常它们是用来放在地址栏的 URL 里的。像 CharField 一样,你可以指定 max_length(也请参阅该部分中的有关数据库可移植性的说明和 max_length)。如果没有指定 max_length, Django 将会默认长度为 50。
我本来是用 pypinyin 在 model save 时自动填充:
from django.db import models
from pypinyin import lazy_pinyin
class Category(models.Model):
"""
节点类别表
"""
name = models.CharField(max_length=128, unique=True, verbose_name="类别名称")
slug = models.SlugField(max_length=128, unique=True, verbose_name="url标识符")
create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
def save(self, *args, **kwargs):
self.slug = slugify("-".join(lazy_pinyin(self.name)))
super(Category, self).save(*args, **kwargs)
class Meta:
verbose_name = "节点类别"
verbose_name_plural = "节点类别列表"
def __str__(self):
return self.name
最近发现已经有轮子 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(' ','-'))