Django model object filter with empty values

22 views
Skip to first unread message

Moreplavec

unread,
Oct 9, 2018, 12:23:38 PM10/9/18
to Django users
Hello,

I have DB with courses and each course has many dates (with starting and ending date). I'm trying to make report with starting and ending course dates in 10 days. The problem is, that one day courses usually don't have ending date (date_stop) filled. Right now i'm using query:

coursedates_ending = CourseDate.objects.all().filter(date_stop__range=[today, today_plus_ten]).order_by('date_stop')

to get courses ending in 10 days. But is it possible to include courses without ending date and for this courses to look at the date_start? Or is it possible to update coursedates_ending with such courses?

Thanks for help or tips how to do it django-way.


Message has been deleted

Mateusz

unread,
Oct 9, 2018, 3:50:50 PM10/9/18
to Django users
There are many ways to resolve your problem. According to https://stackoverflow.com/questions/769843/how-do-i-use-and-in-a-django-filter this should work:
from django.db.models import Q
date_range
= Q(date_stop__range=[today, today_plus_ten])
date_none
= Q(date_start=today, date_stop=None)
coursedates_ending
= CourseDate.objects.filter(date_range & date_none)

You can also consider populating your date_stop with the same day as date_start if it's not specified. Personally, I get take that as the best answer. You can do that either with pre_save signal, which would do it even if that's added from Django Admin page or shell (docs) or form validation only for form(s) (docs).

BTW: Notice, there is no need for X.objects.all().filter(...), you can just use X.objects.filter(...).

Notice: This answer was removed and edited.

Moreplavec

unread,
Oct 9, 2018, 4:43:38 PM10/9/18
to Django users
Thank you, i will solve it with Q, it makes sense and will make it clear in future edits.
Reply all
Reply to author
Forward
0 new messages