我有一個樁模型,看起來像這樣:用其他帖子的鏈接替換標題的最佳方式是什麼?
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])
當我呈現在模板的帖子,我想替換所有鏈接到該職位(例如,提到了文章標題,如果我有一個標題爲'foo'的帖子和其他帖子的內容具有'foo',它將被鏈接到該帖子取代)。
對於我寫了下面的簡單的模板標籤(採用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
不過,我擔心這是要我的網站慢下來的時候有很多的職位。
有沒有一種方法來優化該循環?
我可以將它與pre_save信號掛鉤,但這隻會鏈接到現有的帖子,感覺就像我違反了separation of concerns原則。
最好的辦法是什麼?
編輯:
我應該在cron工作中這樣做嗎?這樣我就不需要處理性能問題,但是我仍然在這裏違反SOC,因爲這不是數據的問題。
在你的項目中,你注意到由此造成的減速? – 2011-03-02 19:16:25
@Ignacio Vazquez-Abrams:這仍在開發中,但我已經輸入了很多帖子來檢查這一點。 – 2011-03-02 19:28:09
在帖子頁面加載後,您可以考慮使用Javascript進行操作。只需使用ajax調用(緩存外)來獲取帖子標題,然後搜索現有頁面並根據需要進行替換。 – Grant 2011-03-02 20:28:56