Let’s imagine we have a base like this:
class MyModel(models.Model):
name = models.CharField(max_lenght=25)
# ... some other fields
dynamic_properties = models.ManyToManyField("Dynamic")
class Dynamic(models.Model):
key = models.CharField(max_lenght=25)
value = models.CharField(max_lenght=25)
MyModel
would be the base of all my entries containing its base static data, but when ever I need to add a dynamic property I add it to the dynamic_properties
field.
While this does make sense on the paper it’s kinda inneficient from what’s I’ve been testing so far, let’s say each MyModel
entries have an average of 4 dynamic properties if I want to iterate over 2k MyModel
objects and return all their dynamic properties it is quite slow.
I tried to use prefetch_related
as the docs suggest but it didn’t seem to have a real impact (but that’s maybe me misunderstanding how it’s used).
For the reference I tried it like that:
{model.name: model.some_value for model in MyModel.objects.all()} # Is very slow
{model.name: model.some_value for model in MyModel.objects.prefetch_related("dynamic_properties")} # Is also very slow
Is there a more efficient way to have dynamic properties or is my understanding of prefetch_related
wrong and this is the good way ?