python - Finding events that happened on the same day in Django -
i have person model , people can have jobs:
class person(models.model): name = textfield() birth_date = datefield() class job(models.model): name = textfield() start_date = datefield() person = foreignkey('person')
i want find people started work on birthday.
now, if wanted find people started work on exact birthday, i'd use:
from django.db.models import f person.objects.filter(birth_date=f('job__start_date'))
but returns no one, because no 1 assigned job born (hopefully).
i can find started work on april 1st:
person.objects.filter(birth_date__month=4, birth_date__day=1)
but, if try combine find people started work during birthday month:
from django.db.models import f person.objects.filter(birth_date__month=f('job__start_date__month'))
i get:
fielderror @ /data/explorer/ cannot resolve keyword u'month' field. join on 'start_date' not permitted
how can find people started work on birthday?
lookups on date(time) fields in f expressions not supported in django. there still way, hacky may be.
from django.db import connection django.db.models import f start_month = connection.ops.date_extract_sql('month', '%s.start_date' % job._meta.db_table) start_day = connection.ops.date_extract_sql('day', '%s.start_date' % job._meta.db_table) birth_month = connection.ops.date_extract_sql('month', 'birth_date') birth_day = connection.ops.date_extract_sql('day', 'birth_date') # trigger join , make job table available # otherwise next query fail (there's less hacky way this) persons = person.objects.filter(job=f('job__pk')) persons.extra( { 'start_month': start_month, 'start_day': start_day, 'birth_month': birth_month, 'birth_day': birth_day }, where=['start_day=birth_day , start_month=birth_month'] )
Comments
Post a Comment