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)])
這不是那麼容易,如果需要顯示的評論不是related_article的頁面上。如何解決主頁,管理員等評論的網址?我使用CBV。 – lampslave
我已經編輯了我的原始答案以迴應你的問題。 –
如果我將使用article_comment.related_article.id,Django將從數據庫獲取文章的所有字段。表現糟糕。 – lampslave