get foreign key objects in a single query - Django

Posted by John on Stack Overflow See other posts from Stack Overflow or by John
Published on 2010-05-14T09:16:37Z Indexed on 2010/05/14 10:14 UTC
Read the original article Hit count: 169

Filed under:
|

Hi

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 records, all of which may or may not have links to ModelB

Now say I want to get a list of every ModelA record along with the data from ModelB

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 runs a query on every instance of i. Thus making 101 queries to run.

Is there any way of running this all in just 1 query. Or at least less than the 101 queries.

I've tried putting in ModelA.objects.select_related().all() but this didn't seem to have any effect.

Thanks

© Stack Overflow or respective owner

Related posts about django

Related posts about django-queries