Mikhail  M
Mikhail M

Reputation: 960

How to decrease number of queries to DB?

I have a model like

class Node(BaseModel, NodeContent):
    __metaclass__ = NodeMetaClass

    node_type  = models.CharField(max_length=16, default='node')
    abs_parent = models.ForeignKey('Node', related_name='all_children', null=True)
... # a lot of other fields

and a code like this

nodes = Node.objects.filter(node_type='comment')
for node in nodes:
    t = node.abs_parent.title

It works but an additional query is executed for each node. I tried to add select_related:

nodes = Node.objects.select_related('abs_parent').filter(node_type='comment')

but this doesn't help. What am I doing wrong?

Upd: @SColvin, thank you for the great method, it works! But actually one field is not enough for me. I'm trying to provide the code that will process nodes further with already loaded .abs_parent objects. This code is already written and awaits interface like node.abs_parent. (maybe with further following through foreign keys). I'm working with the OSQA engine and I'm trying to speed-up it.

Upvotes: 0

Views: 109

Answers (1)

Samuel Colvin
Samuel Colvin

Reputation: 13279

I haven't got Django here, so I can't test it, but you should be able to use

node = Node.objects.filter(node_type='comment')
node_titles = nodes.values_list('abs_parent__title', flat=True)

See here

(Note: I assume since this is the "Djangotronic" way of doing things it should query the db a minimal number of times, but I don't know for sure.)

Upvotes: 2

Related Questions