Daisy McGirr2 min read

Django - Using model functions to generate keyword lists

It's easy to get lost in django and think models need to be complicated. For example if you were creating a blog that you wanted to have keyword tags displayed on the post, the logical solution may be to have a field for each keyword and limiting them to a certain amount.

Well what happens if we want them to have as little or as many as they like without having a load of extra inputs? We could use something as simple as a model function to return a list.

An example blog model:

class Blog(models.Model):
    """
    Blog model
    """
    owner = models.ForeignKey(User, related_name='blog_owner', on_delete=models.CASCADE)
    posted_date = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=250, null=False, blank=False)
    keywords = models.CharField(max_length=500 null=True, blank=True)
    content = RichTextField(max_length=10000, null=False, blank=False)

So we have a keyword char field here, if we added a place holder or label for the user to enter their keywords separated by a comma, we can use a simple function within the model.

def keyword_as_list(self):
    return self.keywords.split(',')

The above code simply splits the words on the comma and will return a list of the keywords. Now to access this on the front end, assuming you have sent a blog object back:

 { % if blog.keywords % }
    <div class="projcard-tagbox">
    { % for keyword in blog.keyword_as_list % }
          <span class="projcard-tag mt-1">{{keyword}}</span>
    { % endfor % }
     </div>
{ % endif % }

First we check if the blog keywords field is not empty, then we can use a for loop to iterate trough the keywords. So we access the object with 'blog' followed by '.keyword_as_list' as our function name.

This will then produce the tags as individual items from our list! Styling of course will be up to you!

Django
Daisy McGirr@Daisy-McG

Software Engineer & Student Mentor

Loading

Loading discussion...

Hey! 👋

Got something to say?

or to leave a comment.