Reputation: 312
Here I have some model and this model should have some tags for making it SEO friendly.For this how can i design my model?
Any suggestions or help would be appreciated.
my model
class TourPackage(models.Model):
name = models.CharField(max_length=255)
package_detail = models.TextField()
image = models.ImageField()
booking_start = models.DateTimeField()
booking_end= = models.DateTimeField()
package_start = models.DateTimeField()
#how can i save this tag field for seo purpose
#tag = models.CharField()
Upvotes: 2
Views: 4773
Reputation: 63
If I understand you correct, you can use Many-To-Many relationship according to the doc. But it implies that each TourPackage model may have many tags against only one as in your example.
You should use something like this
class Tag(models.Model):
name = models.CharField(max_length=255)
class TourPackage(models.Model):
name = models.CharField(max_length=255)
package_detail = models.TextField()
image = models.ImageField()
booking_start = models.DateTimeField()
booking_end= = models.DateTimeField()
package_start = models.DateTimeField()
#how can i save this tag field for seo purpose
tags = models.ManyToManyField('Tag')
And then
tp = TourPackage(...)
tag1 = Tag.objects.create(name='tag1')
tag2 = Tag.objects.create(name='tag2')
tp.tags.add(tag1)
tp.tags.add(tag1)
tp.save()
Upvotes: 5
Reputation: 477607
I advice to make use of a package, like for example django-taggit
[GitHub], this implements a many-to-many field, but with some extra tooling to make managing tags more convenient.
You can install the package, for example with the pip package manager in your virtual environment:
pip install django-taggit
In your settings.py
, you then add 'taggit'
to the INSTALLED_APPS
:
# settings.py
# …
INSTALLED_APPS = [
# …,
'taggit',
# …,
]
Then you can add a TaggableManager
to your model:
from taggit.managers import TaggableManager
class TourPackage(models.Model):
name = models.CharField(max_length=255)
package_detail = models.TextField()
image = models.ImageField()
booking_start = models.DateTimeField()
booking_end = models.DateTimeField()
package_start = models.DateTimeField()
tag = TaggableManager()
Of course this will not add the tags to the page. You will need to write <meta>
tags in your templates to add meta information.
Upvotes: 7