【问题标题】:How to call a model method?如何调用模型方法?
【发布时间】:2016-02-17 11:06:36
【问题描述】:

我试图只显示不超过 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

【问题讨论】:

    标签: python django django-models django-queryset django-managers


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多