2012-06-18 88 views
1

的總和我使用Django的nonrel,Postgre作爲數據庫和蒙戈作爲文件存儲。彙總一個QuerySet得到FileFields大小

我的模型看起來像這樣和正常工作

class Doc(models.Model): 
    created_on = models.DateTimeField(auto_now_add=True) 
    file = models.FileField(storage=gridfs_storage, upload_to='/') 

和工作正常

Doc.objects.all()[0].file.size 
108776 

現在我試圖聚集大小,得到查詢集的總大小。

我已經試過

Doc.objects.all().aggregate(Sum('file__size')) 

但這扔

Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
    File "/Users/zoidberg/dev/backus/lib/python2.6/site-packages/django/db/models/query.py", line 321, in aggregate 
    is_summary=True) 
    File "/Users/zoidberg/dev/backus/lib/python2.6/site-packages/django/db/models/sql/query.py", line 974, in add_aggregate 
    field_list, opts, self.get_initial_alias(), False) 
    File "/Users/zoidberg/dev/backus/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1417, in setup_joins 
    raise FieldError("Join on field %r not permitted. Did you misspell %r for the lookup type?" % (name, names[pos + 1])) 
FieldError: Join on field 'file' not permitted. Did you misspell 'size' for the lookup type? 
    enter code here 

如果這是可能使用ORM或I D必須遍歷文件自己的任何想法?

回答

1

這是不可能與ORM要做到這一點,因爲它只能產生針對數據庫字段集合,而file.size是由存儲後端提供的動態屬性。

這就是說,你可能會更好在上傳時實際數據庫中保存這些信息,這樣就可以避免遍歷所有文件的開銷。

class Doc(models.Model): 
    created_on = models.DateTimeField(auto_now_add=True) 
    file = models.FileField(storage=gridfs_storage, upload_to='/') 
    file_size = models.PositiveIntegerField() 

    def save(self, *args, **kwargs): 
     self.file_size = self.file.size 
     super(Doc, self).save(*args, **kwargs) 

現在聚集按預期方式工作,因爲你正在處理一個數據庫字段:

Doc.objects.all().aggregate(Sum('file_size')) 
+0

權的同時,我用'總和([在Doc.objects.all f.file.size對於f())'但是你的解決方案聽起來更合理。謝謝 ! – Pierre

2

一個hcalves指出,今年採用了直板的ORM是不可能的。我假設你的數據庫已經完成並設置爲什麼你不能這樣做?

total_size = sum([ x.file.size for x in Doc.objects.all() ]) 

只是一個想法嗎?

+0

是的,我回地方自然落下到直到hcalves提出他的解決方案,只是沒有感覺「的Django」的方式:)項目是隔靴搔癢的生產,所以我可以改變我的模型 – Pierre

+0

還卸載總和數據庫可能會比做得更聰明應用程序端 – Pierre