2013-08-18 53 views
0

如果我需要這樣的URL,創建get_absolute_url函數的最佳方法是:「/ article_url#comment-id」?通過外鍵字段使用get_absolute_url的最佳方式

我的模型:

class Article(models.Model): 
    url = models.CharField() 

    def get_absolute_url(self): 
     return reverse('article-detail', args=[self.url]) 

class Comment(models.Model): 
    related_article = models.ForeignKey(Article) 

我的變種:

1)很簡單,但在這種情況下,Django會取物品的各個領域,這是可怕的意見就像「最新10條評論」主頁:

u = self.related_article.get_absolute_url() 
return ''.join([u, '#comment-', str(self.pk)]) 

2)在這種情況下,功能將獨立的Article類的變化,但Django會在第二個查詢第一個查詢網址提取PK:

u = Article.objects.filter(pk=self.related_article_id) \ 
           .only('pk') \ 
           .get() \ 
           .get_absolute_url() 
return ''.join([u, '#comment-', str(self.pk)]) 

3)在這種情況下,現場「網址」被硬編碼,但Django會取pk和網址在一個查詢:我不知道,如果你是存儲越來越多

u = Article.objects.filter(pk=self.related_article_id) \ 
           .only('url') \ 
           .get() \ 
           .get_absolute_url() 
return ''.join([u, '#comment-', str(self.pk)]) 

回答

0

url在您的文章模型中,並提供get_absolute_url,但是,您不需要擔心試圖顯式支持URL中的錨定標記;只要確保您在模板中的標籤中正確設置了標識。

# views.py 
def article_detail(request, article_id): 
    # Proper exception try/except handling excluded: 
    article = Article.objects.get(id=article_id) 
    article_comments = Comment.objects.filter(related_article_id=article_id) 

    return render_to_response('article_detail.html', {'article': article, 
                 'article_comments': article_comments} 

# article_detail.html 
{% for article_comment in article_comments %} 
    <div id='comment-{{article_comment.id}}'> 
     {# Comment information here. #} 
    </div> 
{% endfor %} 

如果你有興趣在超鏈接的評論摘要列表回到原來的文章在評論出現了,那麼你可能是最好的定義註釋模型get_absolute_url功能以及。

編輯:比方說,你是顯示您的主頁,在那裏實際的文章沒有出現在10個最新評論:

# views.py 
def main(request): 
    # Assumes timestamp exists for comments. 
    # Note: This query will get EXPENSIVE as the number of comments increases, 
    #  and should be replaced with a better design for a production environment. 
    latest_article_comments = Comment.objects.all().order_by('creation_date')[:10] 

    render_to_response('main.html', {'latest_article_comments': latest_article_comments}) 


# main.html 
{% for article_comment in article_comments %} 
    <a href="{% url 'article.views.article_detail' article_comment.related_article.id %}#comment-{{article_comment.id}}">{{article_comment.user_comment}}</a> 
{% endfor %} 
+0

這不是那麼容易,如果需要顯示的評論不是related_article的頁面上。如何解決主頁,管理員等評論的網址?我使用CBV。 – lampslave

+0

我已經編輯了我的原始答案以迴應你的問題。 –

+0

如果我將使用article_comment.related_article.id,Django將從數據庫獲取文章的所有字段。表現糟糕。 – lampslave