i am creating a django application from a current database. for better or worse, i've got a handful of sights that i must base my models off. they appear something similar to this:

class Device(Model):
  id = models.IntegerField( primary_key=True, db_column='node_id' )
  name = models.CharField(max_length=127, db_column='node' )
  class Meta:
    db_table = 'node' # db view
    managed = False

class Entity(Model):
  id = models.IntegerField( primary_key=True, db_column='_id' )
  device = models.ForeignKey(Device, db_column='node_id' )
  class Meta:
    db_table = 'entity' # db view
    managed = Fase

so things work okay. however, after i use a template that utilises the ForeignKey it's very slow:

{% for e in entities %}
  {{ e.device.name }}
{% endfor %}

searching in the logs, it seems to become repeating queries for every 'node_id', and ultimately timeout out.

(obviously, if i don't include e.device.name is quick)

it is possible to way i'm able to optimise this?

to become fair, the 'entity' view already has got the title from the device as the second area (node), and so i can use this rather but i'd like the regards to exist.

perhaps you have try .choose_related() inside your view?

entities = Entity.objects.select_related('device').filter(...)

within the other hands, if it's and old database, with no autogenerated by django, most likely node_id might not be a catalog within the database, this can decelerate a great deal any JOIN.