视图上的 Django 外键

发布于 2024-11-10 16:37:11 字数 832 浏览 3 评论 0原文

我正在从现有数据库构建 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北城孤痞 2024-11-17 16:37:11

您是否尝试过 .select_lated() 在您看来?

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

另一方面,如果它是旧数据库,并且不是由django自动生成的,可能node_id可能不是数据库中的索引,这会减慢任何JOIN的速度。

have you try .select_related() in your view?

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文