I'd like to use a function that derives the time that has elapsed since the moment of writing, so please help me

Asked 2 years ago, Updated 2 years ago, 49 views

class Post(models.Model):

    created_date = models.DateTimeField(
        default=timezone.now
        )


    def elasped_time(self):
        now = datetime.now()
        then = self.created_date
        timedelta = now - then
        minutes = timedelta.seconds/60
        return minutes


I'm just a beginner in programming, and I made the model by referring to stackoverflow.

This is from models.py.

By the way, views.py

def post_list(request):
        post_list = Post.objects.all().order_by(elasped_time)
        template = loader.get_template('blog/index.html')
        context = {
            'post_list': post_list,
        }
        return HttpResponse(template.render(context, request))

Trying to run it like this

TypeError at / expected string or bytes-like object

Like this.

post_list = Post.objects.all().order_by(elasped_time) 

This is the problem.

I'm a beginner, what should I do?

I'd appreciate it if you let me know.

Also, can I get the elasped_time I made above as a simple float or integrer value?

I'd like to calculate based on that value.

django

2022-09-22 20:46

2 Answers

I think you'd like to do a chronological sort. You have to write down the field name that is the basis for sorting, but you wrote down the method name.

Post.objects.all().order_by('created_date') Write it down and use it. It should be sorted in the order in which it was written.

If you want to see the latest one, you can write Post.objects.all().order_by('-created_date') and use it.

If you want to see the last 5 minutes of Post, you can do it as follows.

from datetime import datetime, timedelta

five_minute = datetime.now() - timedelta(minutes=5)
Post.objects.filter(created_date__gt=five_minute)

For more information on how to use created_date__gt, see here .


2022-09-22 20:46

If you want to get the current time from the store, it is better to use django.utils.timezone.now() rather than datetime.datetime.now().

This is because the default DateField/DateTimeField in the warehouse has timezone information, but datetime.now() does not contain timezone information.

from django.utils import timezone
from datetime import timedelta

five_minute = timezone.now() - timedelta(minutes=5)
Post.objects.filter(created_date__gt=five_minute)

‐ AskDjango


2022-09-22 20:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.