我正在尝试在 django 中创建一个 slug 字段,它需要使用来自 2 个不同表的 2 个表字段。
解决这个问题的最佳方法是什么?
例如: 如果我有一个带有
restaurant_name
字段的餐厅表和带有 location_name
字段的位置表,如何从这两个值创建 slug 字段?即,由 Restaurant_name + location_name 生成的 slugfield
编辑:
如果可能的话,我想在解决方案中使用 AutoSlug Field。例如,这里是一个带有单个字段的实现:
class Cuisine(models.Model):
name = models.CharField(max_length=100)
name_slug = AutoSlugField(populate_from='name', unique=True, null=True)
def __str__(self):
return self.name
这很简单,您实际上不必为 AutoSlugField 编写一些特殊的处理程序。
from django.utils.text import slugify
class Restaurant(models.Model):
name = models.CharField(max_length=100)
location = models.ForeignKey(Location)
name_slug = models.AutoSlugField(populate_from='name', unique=True, null=True)
def save(self, *args, **kwargs):
'''
Assuming that you don't have a slug field on your other model
This will simply add the extra slug to your restaurant name.
Personally, i would also add a slug field to the location table so you
simply call location.slug and don't have to slugify()
'''
self.name_slug += slugify(self.location.name)
super(Restaurant, self).save(*args, **kwargs)
这里要记住的一件事是,django-autoslug 没有在其 AutoSlugField 中提及任何有关特殊 max_length 的内容,该字段的 max_length 可能会出现问题。
所以替代解决方案比上面简单得多:
from django.utils.text import slugify
class Restaurant(models.Model):
name = models.CharField(max_length=100)
location = models.ForeignKey(Location)
# sum both fields max_length for the slug
name_slug = models.SlugField(max_length=200, unique=True, null=True)
def save(self, *args, **kwargs):
# just check if name or location.name has changed
self.name_slug = '-'.join((slugify(self.name), slugify(self.location.name)))
super(Restaurant, self).save(*args, **kwargs)
p.s:您可以使用正确的型号名称进行编辑。
根据文档,我对使用 Django 的 AutoSlug lib 进行的死后发布感到抱歉:
# autoslugify value from a custom callable
# (ex. usage: user profile models)
slug = AutoSlugField(populate_from=lambda instance: instance.user.get_full_name())
所以,我认为您可以通过以下方式解决您的问题:
class Restaurant(models.Model):
name = models.CharField(max_length=100)
location = models.ForeignKey(Location)
slug_name = AutoSlugField(populate_from=lambda instance: f"{instance.name} {instance.location"
输出将与 slugify("Name Location") 相同,因此“name-location”