Search code examples
pythondjangodjango-modelsdjango-querysetdjango-managers

How to call a model method?


I am trying to display only objects, which are not older then 4 days. I know I can use a filter:

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

but I really want to use a modal method for exercise.

The method is defined in model Book and is called published_recetnly.

So my question is how to call a modal method in views.py?

This is my current code:

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

Solution

  • Maybe you should use a manager in this case. It's more clear and you can use it to retrieve all published recently books.

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

    Set like this your managers file:

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

    And now, you can filter more clearly in your views file.

    Books.objects.published_recently()