Assuming you have a date value from model B
, calculate two dates: one - 2 years in the past and another - 2 years in the future by the help of python-dateutil
module (taken partially from here). Then, use __range
notation to filter out A
records by date range:
from dateutil.relativedelta import relativedelta
def yearsago(from_date, years):
return from_date - relativedelta(years=years)
b_date = b.my_date
date_min, date_max = yearsago(b_date, 2), yearsago(b_date, -2)
data = A.objects.filter(my_date__range=(date_min, date_max))
where b
is a B
model instance.
Also see: Django database query: How to filter objects by date range?
Hope that helps.