如何调用模型方法?
How to call a model method?
我试图只显示不超过 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
在这种情况下,也许您应该使用经理。更清晰,你可以用它来检索所有最近出版的书籍。
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()
我试图只显示不超过 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
在这种情况下,也许您应该使用经理。更清晰,你可以用它来检索所有最近出版的书籍。
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()