I have a post model th开发者_开发知识库at looks like this:
class Post(models.Model):
slug = AutoSlugField(populate_from = 'title', unique = True)
title = models.CharField(max_length = 200)
content = models.TextField(blank = True)
is_published = models.BooleanField(default = False)
created_on = models.DateField(auto_now = True)
def get_absolute_url(self):
return reverse('post', args = [self.slug])
When I render the post in a template I would like to replace all mentions of a post title with a link to that post (e.g. if I have a post entitled 'foo' and another posts' content has 'foo' it will be replaced with a link to the post).
For that I have written the following simple template tag (uses django-classy-tags):class LinkBack(Tag):
options = Options(
Argument('posts', required = True),
'for',
Argument('content', required = True)
)
def render_tag(self, context, posts, content):
output = content
for post in posts:
output = output.replace(post.title, '<a href="%s">%s</a>' % (post.get_absolute_url() , post.title))
return output
However I fear that this is going to slow down my website when there are many posts.
Is there a way to optimize that loop? I could hook it to the pre_save signal but that will only link to existing posts and it feels like I am violating the separation of concerns principle. What's the best way to do it?EDIT:
Should I be doing this in a cron job? That way I won't need to deal with the performance issue, however I am still violating SOC here since this is not the data's problem.Yes, in time this will become even more expensive as the number of posts increase. But, there's a much better approach to have this done. When you consider the use case, you need to know the exact post title for this to work. So, if your already browsing around your site to get the exact title of some post, you should inevitably also come across the post's URL, right? What your doing is creating a clever mechanism that will take raw post titles and magically render them as references to an existing post on your site, but what you should be doing is creating an explicit reference as the post author and defer from any unnecessary post-processing.
Implement support for creating references, be it other posts or some other resources, located on your website or somewhere else. SO, for instance, uses Markdown for creating references via the syntax [Title][#]
pointing to the list [#]: http://path.to
, but there are many others. I know there are many questions relating to markup languages, some with editors in Django specifically, so I'm sure you can settle on something and have it plugged into your Django instance in no time.
精彩评论