How to do tags in django with mariadb

im trying to make a website and part of that is having tags much like this site has, do you have advice? rn im trying this

def index(request):
    storylist = Story.objects.order_by("id")
    tagslist = []
    for sto in storylist:
        tagslist.append(sto.tags.split(","))
    context = {"storylist": storylist,"tagslist":tagslist}
    return render(request, "storyage/index.html", context)

but

  1. its not working (i dont know how to make the specific tags show up with the specific story)

  2. deleting a story breaks the whole thing i feel

Here you are storing the tags in a comma-separated string inside your Story model and trying to maintain a separate tagslist; But the issue with this is that storylist and tagslist will become coupled by position, in which case when you delete a story, the indices will no longer line up the way you would've expected when you don't update tagslist and things will break.

A solution for this and particularly to make the tag management easier would be to create a separate Tag model and use ManyToManyField:

class Tag(models.Model):
    name = models.CharField(max_length=50, unique=True)
    
    def __str__(self):
        return self.name

class Story(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    tags = models.ManyToManyField(Tag, related_name='stories')
    created_at = models.DateTimeField(auto_now_add=True)

def index(request):
    storylist = Story.objects.order_by("id").prefetch_related("tags")
    context = {"storylist": storylist}
    return render(request, "storyage/index.html", context)

And then your Django code would accordingly look something like this:

{% for story in storylist %}
    <div class="story">
        <h3>{{ story.title }}</h3>
        <div class="tags">
            {% for tag in story.tags.all %}
                <span class="tag">{{ tag.name }}</span>
            {% endfor %}
        </div>
    </div>
{% endfor %}
Вернуться на верх