Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a slug field from 2 different values in 2 different tables in Django

Tags:

python

django

I'm trying to create a slug field in django that requires the use of 2 table fields from 2 different tables.

What is the best way of going about this?

For example: If I had a Restaurant table with a restaurant_name field and a Location table with a location_name field, how do I create a slug field from these two values? That is, a slugfield generated from restaurant_name + location_name

EDIT:

If possible, I would like to use AutoSlug Field in the solution. For example here is an implementation with a single field to 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
like image 647
Michael Smith Avatar asked Jan 02 '26 07:01

Michael Smith


1 Answers

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.

like image 85
HassenPy Avatar answered Jan 03 '26 20:01

HassenPy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!