如何在 Django 中创建一个独特的 slug [英] How to create a unique slug in Django
问题描述
我正在尝试在 Django 中创建一个独特的 slug,以便我可以通过这样的 url 访问帖子:http://www.example.com/buy-a-new-bike_Boston-MA-02111_2
I am trying to create a unique slug in Django so that I can access a post via a url like this: http://www.example.com/buy-a-new-bike_Boston-MA-02111_2
相关模型:
class ZipCode(models.Model):
zipcode = models.CharField(max_length=5)
city = models.CharField(max_length=64)
statecode = models.CharField(max_length=32)
class Need(models.Model):
title = models.CharField(max_length=50)
us_zip = models.CharField(max_length=5)
slug = ?????
def get_city():
zip = ZipCode.objects.get(zipcode=self.us_zip)
city = "%s, %s %s" % (zip.city, zip.statecode, zip.zipcode)
return city
示例邮政编码记录:
- 邮政编码 = "02111"
- city = "波士顿"
- statecode = "MA"
样本需求记录:
- title = "买一辆新自行车"
- us_zip = "02111"
- slug = "buy-a-new-bike_Boston-MA-02111_2"(需要)
关于如何制作这种独特的蛞蝓有什么提示吗?它的组成是:
Any tips as to how to create this unique slug? Its composition is:
- Need.title + "_" + Need.get_city() + "_" + 一个可选的递增整数以使其唯一.所有空格都应替换为-".
注意:上面我想要的 slug 假设 slugbuy-a-new-bike_Boston-MA-02111"已经存在,这就是它附加了_2"以使其独一无二.
NOTE: My desired slug above assumes that the slug "buy-a-new-bike_Boston-MA-02111" already exists, which is what it has the "_2" appended to it to make it unique.
我尝试过 django-extensions,但它似乎只能使用一个字段或字段元组来构造唯一的 slug.我需要传入 get_city() 函数以及标题和城市之间的_"连接器.有人解决了这个问题并愿意分享吗?
I've tried django-extensions, but it seems that it can only take a field or tuple of fields to construct the unique slug. I need to pass in the get_city() function as well as the "_" connector between the title and city. Anyone solved this and willing to share?
谢谢!
更新
我已经在它的 UUIDField 中使用了 django 扩展,所以如果它也可以用于它的 AutoSlugField 就好了!
I'm already using django-extensions for its UUIDField, so it would be nice if it could also be usable for its AutoSlugField!
推荐答案
我使用这个 snippet生成独特的 slug 和我典型的保存方法如下
I use this snippet for generating unique slug and my typical save method look like below
slug 将是带有 blank=True 的 Django SlugField 但在 save 方法中强制执行 slug.
slug will be Django SlugField with blank=True but enforce slug in save method.
Need 模型的典型保存方法可能如下所示
typical save method for Need model might look below
def save(self, **kwargs):
slug_str = "%s %s" % (self.title, self.us_zip)
unique_slugify(self, slug_str)
super(Need, self).save(**kwargs)
这将生成像 buy-a-new-bike_Boston-MA-02111 、buy-a-new-bike_Boston-MA-02111-1 等的 slug.输出可能略有不同,但您始终可以浏览代码片段并根据需要进行自定义.
and this will generate slug like buy-a-new-bike_Boston-MA-02111 , buy-a-new-bike_Boston-MA-02111-1 and so on. Output might be little different but you can always go through snippet and customize to your needs.
这篇关于如何在 Django 中创建一个独特的 slug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!