2011-04-16 26 views
0

我使用get_absolute_url方法來獲取動態查詢的url,但是當顯示鏈接時,它只顯示get_absolute_url方法中的第一個參數,而不是第二個參數。只有當我使用模型的ForeignKey作爲第一個參數時,它纔會這樣做。以下是代碼。Django的get_absolute_url與ForeignKey參數不起作用

class Topic(models.Model): 
topic_id = models.AutoField(primary_key=True) 
forum_id = models.ForeignKey(Forum) 
topic_title = models.CharField(max_length=400) 
topic_date_time = models.DateTimeField(auto_now_add=True) 
topic_user_id = models.IntegerField() 
topic_views = models.IntegerField(default=0) 
topic_replies = models.IntegerField(default=0) 
topic_is_locked = models.BooleanField(default=False) 
topic_is_sticky = models.BooleanField(default=False) 

def __unicode__(self): 
    return '%s' % _(u'self.topic_title') 

def get_absolute_url(self): 
    **return '/forums/%i/%i/' % (self.forum_id, self.topic_id)** 

我該如何解決這個問題?謝謝!

+0

究竟是從'topic_instance.get_absolute_url()'返回的字符串? – Puddingfox 2011-04-16 17:35:32

+0

你能不能展示你的urls.py的相應部分?儘管使用permalink-decorator來反轉你的url可能會更好(http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#django.db.models.permalink) – arie 2011-04-16 17:35:34

+0

我找到了我的問題的答案,但也一定會考慮到這一點。謝謝! – vol4life27 2011-04-16 18:26:32

回答

1
def get_absolute_url(self): 
    return '/forums/%s/%s/' % (str(self.forum_id.pk), self.topic_id) 

編輯:jerzyk評論提到這些點:

  1. 使用@permalink與get_absolute_url和使用視圖和參數,這樣你就不必硬編碼的網址逆轉的URL。

  2. 使用_id代替的.pk

    def get_absolute_url(self): 
        return '/forums/%s/%s/' % (self.forum_id_id, self.topic_id) 
    
+0

這工作完美。謝謝! – vol4life27 2011-04-16 18:26:01

+1

但是這是每次執行時生成額外的數據庫查詢,更好的紅外將是:'/ forums /%i /%i /'%(self.forum_id_id,self.topic_id),另一個故事是,這不是好方法,更好的辦法是使用永久鏈接裝飾器http://docs.djangoproject.com/en/1.3/ref/models/instances/#django.db.models.permalink – Jerzyk 2011-04-16 18:50:31