简体   繁体   中英

How to get the Modelfield - datetime.now

i've been strugling a lot with arithmetics on Dates. First of all i got the date between two datetimeFields (models) and thats ok. but i'd like to get the (To_do.end)-datetime.now()

i've got the 2 datefields difference by the :
To_do.objects.annotate( delta=ExpressionWrapper(F('end') - F('start'), output_field=DurationField())

since i've been trying the same with a variable=datetime.now() and still don't get it

thats the test that im trying to get the succes

def index(request):
    myDate = datetime.now()
    days_left1 = To_do.objects.annotate(
        delta=ExpressionWrapper(F('end') - myDate, output_field=DurationField()))
    return render(request, 'ongoingtest.html', {
        'myDate': myDate,
        'days_left1': days_left1,
    })

thats what i did to get the difference between the two model fields

class HomeView(ListView):
    template_name = 'ongoing.html'
    model = To_do

    def get_queryset(self):
        return To_do.objects.annotate(
            delta=ExpressionWrapper(F('end') - F('start'), output_field=DurationField())
        )

models.py:

class To_do (models.Model):
    task = models.CharField(max_length=150)
    topic = models.CharField(max_length=150)
    how = models.TextField(max_length=600)
    start = models.DateTimeField(auto_now_add=True)
    end = models.DateTimeField(blank=False)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.task

just get the To_do.end - datetime.now()

Use the Now database function: https://docs.djangoproject.com/en/2.2/ref/models/database-functions/#now

from django.db.models.functions import Now

def index(request):
    myDate = datetime.now()
    days_left1 = To_do.objects.annotate(
        delta=ExpressionWrapper(F('end') - Now(), output_field=DurationField()))
    return render(request, 'ongoingtest.html', {
        'myDate': myDate,
        'days_left1': days_left1,
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM