Domanda

I have a query on some Django models with a ForeignKey, and I've noticed that it means there are multiple database calls, that perhaps should not be necessary.

This are my models:

class Store(models.Model):
    name = models.CharField(max_length=100) 
class Computer(models.Model):
  model = models.CharField(max_length=500)
  store = models.ForeignKey(Store)

My view:

results = Computer.objects.filter(model=model)

And this is my template:

{% for result in results %}
<li class="result">
{{ result.name }} from {{ result.store.name }}
</li>
{% endfor %}

Using django-debug-toolbar I can see that there is one database call to get the results: SELECT ••• FROM "mydb_computer"/, as I'd expect.

But then there are many more database calls (one for each result) to get the store name: SELECT ••• FROM "mydb_store" WHERE "computer_store"."id" = 27 etc.

Is there some way I can make the store name a property of the item, to avoid these multiple database calls?

È stato utile?

Soluzione

select_related should do what you want it to:

results = Computer.objects.filter(model=model).select_related('store')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top