How To Set A Timedelta In Between Two Model Datefields
i'm strugling some time already trying to set a timedelta in two fields of my model, then display de difference between then.
i've tried Stack and a lot of others tutorials and not quite shure if a should make a function on my models or my views, or a basic variable on the views i've tried all of them here is my code:
from django.db import models from datetime import datetime from datetime import timedelta 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.DateField(blank=False) end = models.DateField(blank=False) def __str__(self): return self.task VIEWS.PY class DetailView(DetailView): template_name = 'details.html' model = To_do def get_queryset(self): return To_do.objects.all() def get_delta(self): d1 = To_do.start d2 = To_do.end tdelta = d1-d2 return tdelta
i want to display the difference between the star and end and after that, and after that setup an alarm if get less than three days. appreciate your help.
You can annotate your queryset to calculate the difference, like:
from django.db.models import DurationField, ExpressionWrapper, F class DetailView(DetailView): template_name = 'details.html' model = To_do def get_queryset(self): return To_do.objects.annotate( delta=ExpressionWrapper(F('end') - F('start'), output_field=DurationField()) )
The object that arises from this queryset will have an extra field
delta here that is a
timedelta object that contains the difference between the end and the start.
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module