我试图在django中创建一个slug字段,需要使用来自2个不同表的2个表字段。
解决这个问题的最佳方式是什么?
例如:
如果我有一个带有restaurant_name
字段的餐厅表和一个带有location_name
字段的位置表,如何从这两个值创建一个段塞字段?也就是说,从restaurant_name + location_name
修改:
如果可能,我想在解决方案中使用AutoSlug Field。例如,这里是一个具有单个字段来实现slugify的实现:
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
答案 0 :(得分:1)
这很简单,你不必为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:您可以使用正确的型号进行编辑。