2016-03-10 20 views
0

我有一個這樣的模型中,這功能在models.py到管理,所以可以控制

class Post(models.Model): 
    title = models.CharField(max_length = 50) 

    def get_vote_count(self): 
     """This function is intended to return count of voted on thread. 
     :return: The sum of vote, upvote - devote 
     """ 
     vote_count = self.vote_set.filter(is_up=True).count() - self.vote_set.filter(is_up=False).count() +1 
     if vote_count >= 0: 
      return "+ " + str(vote_count) 
     else: 
      return "- " + str(abs(vote_count)) 

和vote_count被顯示爲這樣的; post.get_vote_count,我希望能夠在我的admin.py中進行控制。

我試圖像這樣

class PostAdmin(admin.ModelAdmin): 
    fields = ['vote_count'] 

    class Meta: 
     model = Post 

但正在顯示什麼,有人可以幫我嗎?

回答

1

使用moidel方法時,還需要將它們添加到readonly_fields列表中。

class PostAdmin(admin.ModelAdmin): 
    fields = ['vote_count'] 
    readonly_fields = ['vote_count'] 
    class Meta: 
     model = Post 

https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

+0

謝謝你,但我沒有得到控制,它只是顯示vote_count – winixxee

+1

的價值。如果你需要的是可編輯的,則需要將其添加爲一個模型字段(如標題)。 –

+0

ah-ha謝謝先生 – winixxee

相關問題