[Django]-Creating a slug field from 2 different values in 2 different tables in Django

3👍

This is simple, you don’t really have to write some special handler for you 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)

One thing to keep in mind here is that the django-autoslug doesn’t mention anything about special max_length to their AutoSlugField, there will probably be problems with max_length for this field.

So an alternative solution is way simpler than the above:

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: you can make an edit with the right model names.

Leave a comment