0

我正在嘗試僅顯示不比4天大的對象。我知道我可以使用一個過濾器:如何調用模型方法?

new = Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4)) 

但我真的想使用模態方法進行鍛鍊。

該方法在模型Book中定義,稱爲published_recetnly。

所以我的問題是如何調用views.py中的模態方法?

這是我當前的代碼:

views.py

def index(request): 
    new = Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4)) 
    return render_to_response('books/index.html', {'new':new}, context_instance=RequestContext(request)) 

的index.html

{% if book in new %} 
    {{ book.title }} 
{% endif %} 

models.py

class Book(models.Model) 
    pub_date = models.DateTimeField('date published') 

    def published_recently(self): 
     now = timezone.now() 
     return now - datetime.timedelta(days=4) <= self.pub_date <= now 

回答

5

也許你應該使用管理在這種情況下。它更清楚,你可以用它來檢索所有最近出版的書籍。

from .managers import BookManager  
class Book(models.Model) 
    pub_date = models.DateTimeField('date published') 
    objects = BookManager() 

這樣設置你的經理文件:

class BookManager(models.Manager): 
    def published_recently(self,): 
     return Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4)) 

而現在,你可以在你的意見的文件更清晰過濾器。

Books.objects.published_recently()