Hi,
I have 3 models like below and I want to get all Events and Parameters related to each event through the middle model ParameterSet. This is similar to the vegetarian_pizza example in the documentation, but I still have trouble making it work.
from django.db import models
class EventVersion(models.Model):
... # other fields
class ParameterSet(models.Model):
event = models.ForeignKey("event.EventVersion", related_name="parametersets", on_delete=models.CASCADE)
preferred = models.BooleanField(default=False)
... # other fields
class Parameter(models.Model):
name = models.CharField(max_length=255)
parameterset = models.ForeignKey(ParameterSet, default=1, on_delete=models.CASCADE)
... # other fields
Naively, this is what I want to do:
events = EventVersion.objects.all()
for event in events:
default_parameters = Parameter.objects.filter(
parameterset__preferred=True,
parameterset__event=event
)
for param in default_parameters:
# do some work, no more DB hits
This will make a DB query for each event, for which there are a LOT, and it’s making the page slow. So I thought of pre-fetching all the parameters. This is what I tried:
defparams = Parameter.objects.filter(parameterset__preferred=True)
events = EventVersion.objects.prefetch_related(
Prefetch(
"parametersets__parameter_set",
queryset=defparams,
to_attr="default_parameters"
)
)
for event in events:
for param in event.default_parameters:
# do some work, no more DB hits
print(param.name)
Traceback (most recent call last):
File "<console>", line 2, in <module>
AttributeError: 'EventVersion' object has no attribute 'default_params'
Am I doing this right? The FK relations go in the opposite way than the example in the docs, but I think it should also work.