'Getting all objects of a model with ForeignKey field results in slow and a lot of query calls

When using the ModelChoiceField I am passing all the objects via

brand = forms.ModelChoiceField(queryset=MobileModel.objects.all())

The model is as follows:

class MobileModel(models.Model):
        brand = models.ForeignKey(MobileBrand, on_delete=models.PROTECT, blank=True, null=True)
        ....

When checking with the debugger I see SQL query is called for every mobile model rows for getting the brand.

Which for large records ends up with huge SQL queries.

How to solve it and reduce the foreign key SQL queries.



Solution 1:[1]

To reduce the query calls and get all foreign key values I had to use select_related

The queryset becomes like this:

mobile_models_all = MobileModel.objects.select_related('brand').all()

With this, I ended up reducing my query calls from around 3000 to only 7!!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rashed Mazumder