I have 2 models in my django code:
class ModelA(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) created_by = models.ForeignKey(User) class ModelB(models.Model): category = models.CharField(max_length=255) modela_link = models.ForeignKey(ModelA, 'modelb_link') functions = models.CharField(max_length=255) created_by = models.ForeignKey(User)
Say ModelA has 100 entries, all of which may or may not have links to ModelB
Now say I want to get a list of each ModelA record along with ModelB data
I would do:
list_a = ModelA.objects.all()
Then, to get the data for ModelB, I would have to do
for i in list_a: i.additional_data = i.modelb_link.all()
However, this triggers a query for each instance of i. Thus, 101 queries are executed.
Is there a way to run all this in just one request. Or at least less than 101 queries.
I tried to insert ModelA.objects.select_related().all() , but it showed no effect.
thanks
python django django-queryset
John
source share