2009-05-26 57 views
1

該網站使用2個對象 - 文章和博客。每次查看文章或博客時,相關櫃檯應增加一個。Django Contenttypes和裝飾

這個想法是有一個「前十名」的應用程序,用於衡量文章和條目的「流行度」。

因爲我使用多個對象,我希望跟蹤器模型使用genericForeignKey來關聯對象。

#models.py 
class Tracker(models.Model): 
    count = models.PositiveIntegerField(default=1) 
    content_type = models.ForeignKey(ContentType) 
    object_id = models.PositiveIntegerField() 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 
    def hit(self): 
     self.count += 1 

我想寫一個包裝視圖函數的裝飾器,但它可能沒有必要。

謝謝

回答

2

如果我明白你對你要計算每個對象的每個實例。我會通過使用post_initsignal - 如果你不介意它不是裝飾者。

下面是一個代碼,我寫了 - 使用post_save代替post_init的:

def thumb_init(sender, **kwargs): 
    kwargs['instance'].process() 
    kwargs['instance'].make_thumbnail() 

post_init.connect(thumb_init, sender=Thumbnail) 
post_init.connect(thumb_init, sender=<otherModel here>) 
+0

所以每當數據庫被擊中的對象的查詢發送一個post_init信號?通過用計數器收聽和響應信號,我們可以計算一個特定「實例」在視圖中被實例化了多少次。真棒! – 2009-05-27 00:39:54