视图上的 Django 外键
我正在从现有数据库构建 django 应用程序。无论好坏,我有一些观点,我想将它们作为我的模型的基础。它们看起来像这样:
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
所以一切正常。但是,当我尝试使用利用外键的模板时,速度非常慢:
{% for e in entities %}
{{ e.device.name }}
{% endfor %}
查看日志,它似乎正在重复查询每个“node_id”,并最终超时。
(当然,如果我不包含e.device.name
一切都很快)
有没有办法可以优化这个?
公平地说,“实体”视图已经将设备名称作为另一个字段(节点
),因此我可以使用它,但我希望存在这种关系。
i'm building a django app from an existing database. for better or worse, i have a couple of views that i would like to base my models off. they look something like 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, when i try to use a template that utilises the ForeignKey it is very slow:
{% for e in entities %}
{{ e.device.name }}
{% endfor %}
looking at the logs, it appears to be repeating queries for each 'node_id', and ultimately timeout out.
(of course, if i do not include e.device.name
is all quick)
is there a way i can optimise this?
to be fair, the 'entity' view already has the name of the device as another field (node
), so i could use this instead but i would like the relation to exist.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过 .select_lated() 在您看来?
另一方面,如果它是旧数据库,并且不是由django自动生成的,可能node_id可能不是数据库中的索引,这会减慢任何JOIN的速度。
have you try .select_related() in your view?
in the other hand, if it is and old database, and no autogenerated by django, probably node_id may not be an index in the database, this will slow down a lot any JOIN.