2017-02-05 50 views
0

我正在試圖製作一個網站,人們可以創建一個活動,然後添加圖片(從外部相冊,無需上傳),然後我想拉取有關信息添加了多少圖片並將其顯示在中央目錄上。例如(不包括爲簡潔起見一些代碼):計數Django中非空字段的數量

models.py

class EventDB(models.Model): 
    picture1 = models.CharField ("picture 1", max_length=255, blank=True) 
    picture2 = models.CharField ("picture 2", max_length=255, blank=True) 

如果有人加入一個項目EventDB並添加1點的畫面,我可以返回輸出爲1。如果他們增加了2張圖片,它會返回2,依此類推。

我想要一箇中央頁面,列出所有的事件,並有相應數量的圖片旁邊。例如:

事件1(2)

事件2(1)

EVENT3(4)

其中括號中的數字是圖片的#。什麼是最好的方法來做到這一點?我嘗試過玩(picture1__isnull = True).count(),但是在沒有上傳圖片1的情況下,我計算了我的數據庫中的總數。

謝謝!

回答

0

添加屬性或功能,將計算的圖片總數爲您提供:

class EventDB(models.Model): 
    picture1 = models.CharField ("picture 1", max_length=255, blank=True) 
    picture2 = models.CharField ("picture 2", max_length=255, blank=True) 

    def picture_count(self): 
     fields = self._meta.get_fields() 
     n_count = len([ x for x in fields if getattr(self, field.name) ]) 
     return n_count  

或者,你可以寫一個F功能,將做註釋爲你的數據庫。函數的語法將根據您的數據庫而有所不同。