Home > other >  How to calculate date between different fields in two querysets with same foreign key in Django
How to calculate date between different fields in two querysets with same foreign key in Django

Time:11-22

I am using Django. Is there a way to count between different fields in a queryset with the same foreign key??!!

That is, we want to subtract register_date from injection_date. You want to get (2021-1-03) - (2021-10-31) = 3days.

injection_date enroll_date student_id (외래키)
2021-10-31 52
2021-11-03 52

Below is the code I've written so far, how do I fix it?! Please help. [models.py]

class Student(models.Model):
    name = models.CharField(max_length=500, blank=True, null=True)
    ...

class Feedback(models.Model):
    injection_date = models.DateField(blank=True, null=True)
    enroll_date = models.DateField(blank=True, null=True)
    student_id = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True, blank=True)

[views.py]

injection_enroll = Feedback.objects\
          .annotate(enroll_injection=F('enrolL_date') - F('injection_date'))

CodePudding user response:

This will get you all students annotated with their max enroll_date minus their min injection_date. The min/max is for removing duplicate values that may occur for a student

Student.objects.annotate(
    injection_date=Min('feedback__injection_date'),
    enroll_date=Max('feedback__enroll_date')
).annotate(
    enroll_injection=F('enroll_date') - F('injection_date')
)

CodePudding user response:

Try this one:

from django.db.models import IntegerField, F
from django.db.models.functions import Cast, ExtractDay, TruncDate


injection_enroll = Feedback.objects.annotate(
    enroll_injection=Cast(
        ExtractDay(TruncDate(F('enrolL_date')) - TruncDate(F('injection_date'))),
        IntegerField()
    )
)

CodePudding user response:

from django.db.models import F
my_list = todolist.objects.order_by('injection_date').filter(created__gte=F('enroll_date'))

Template:

{% if my_list %}
{% for list in my_list %}
{{ list.text}}
{% endfor %}
{% else %}
<p>there is no list</p>
{% endif %}

In the end I get an empty list, but I know, it is not correct. I have also used the following inside the template (without queryset filter):

{% if list.created|date:'d m y h:i:s' == list.modified|date:'d m y h:i:s' %}

It worked, but I would prefer to see a more elegant solution.

  • Related