Answer the question
In order to leave comments, you need to log in
How to filter by date range from related table?
Task:
There are 2 tables: Car Make and Car Model
class Manufacturer(models.Model):
title = models.CharField(_("Full name"), max_length=255, blank=True)
class CarModel(models.Model):
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.PROTECT, related_name="models_car")
production_start = models.DateField(null=True, blank=True)
production_end = models.DateField(null=True, blank=True)
Manufacturer:
id title
===========
1 Audi
2 BMW
Model:
mfa_id start end
=========================
1 1932 1960
1 1980 2001
2 1977 2014
2 2004 ----
Answer the question
In order to leave comments, you need to log in
Did it like this:
def get_mfa(year):
year = date(int(year), 1, 1)
cm = CarModel.objects.filter(Q(production_end__gte=d) | Q(production_end=None), production_start__lte=d)
return Manufacturer.objects.filter(models_car__in=cm).distinct()
If you have production_start
and production_end
it's only a year, there's no need to do them DateField
. If you make them PositiveIntegerField
, or at all PositiveSmallIntegerField
, it will be possible to make them simpler and more efficient:
def get_mfa(year):
return CarModel.objects.filter(
Q(production_start__lte=year) | Q(production_start__isnull=True),
Q(production_end__gte=year) | Q(production_end__isnull=True)
).values_list('manufacturer', flat=True).distinct()
production_start
, production_end
or both may be absent. .filter(models_car__in=cm)
. If the list cm
grows to hundreds or thousands of elements, imagine how gigantic the SQL query will become using it and how much memory it eats up.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question