如何调用模型方法?

Ivi*_*vic 0 python django django-models django-queryset django-managers

我试图只显示不超过4天的对象.我知道我可以使用过滤器:

new = Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4))
Run Code Online (Sandbox Code Playgroud)

但我真的想用一种模态方法进行锻炼.

该方法在模型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))
Run Code Online (Sandbox Code Playgroud)

的index.html

 {% if book in new %}
    {{ book.title }}
 {% endif %}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

小智 5

也许你应该在这种情况下使用经理.它更清晰,您可以使用它来检索所有已发布的最近的书籍.

from .managers import BookManager    
class Book(models.Model)
    pub_date = models.DateTimeField('date published')
    objects = BookManager()
Run Code Online (Sandbox Code Playgroud)

像这样设置您的经理文件:

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

现在,您可以在视图文件中更清晰地过滤.

Books.objects.published_recently()
Run Code Online (Sandbox Code Playgroud)