Reputation: 138
I am building a tiny website host service, where an user can create a website and insert pages in it.
So I created the following classes:
class Website(models.Model):
account = models.CharField(max_length=30, unique=True)
custom_domain = models.CharField(max_length=130, blank=True, unique=True) #optional
title = models.CharField(max_length=80)
class Page(models.Model):
website = models.ForeignKey(Website)
title = models.CharField(max_length=80)
slug = models.CharField(max_length=80, unique=True)
content = models.TextField()
I want to make the field 'slug' unique only to the relationship between Website and Page classes. This way two sites can have a page with the same slug. Like this:
http://mysite.com/website_1/contact_page
http://mysite.com/webiste_2/contact_page
But the field option 'unique' is intended for that.
Any tips or best practices in cases like this?
Upvotes: 0
Views: 81
Reputation: 32542
Drop the unique requirement on the slug column and add a unique_together
to the Page
's Meta
class.
class Page(models.Model):
website = models.ForeignKey(Website)
title = models.CharField(max_length=80)
slug = models.CharField(max_length=80)
content = models.TextField()
class Meta:
unique_together = ('website', 'slug')
Upvotes: 1