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()