Django admin 导致一个模型负载过高
在我的 Django 管理中,当我尝试查看/编辑某个特定模型类中的对象时,内存使用量和 CPU 会急剧上升,我必须重新启动服务器。我可以很好地查看对象列表,但当我单击其中一个对象时就会出现问题。其他型号都还好。在代码中使用对象(即创建和显示)是可以的,只有当我尝试使用管理界面查看对象时才会出现问题。这门课甚至没有什么特别的异国情调:
class Comment(models.Model):
user = models.ForeignKey(User)
thing = models.ForeignKey(Thing)
date = models.DateTimeField(auto_now_add=True)
content = models.TextField(blank=True, null=True)
approved = models.BooleanField(default=True)
class Meta:
ordering = ['-date']
有什么想法吗?我很困惑。我能想到的唯一原因可能是 thing
是一个相当大的对象(几 kb),但据我了解,它在需要时才会被加载(正确吗?) 。
In my Django admin, when I try to view/edit objects from one particular model class the memory usage and CPU rockets up and I have to restart the server. I can view the list of objects fine, but the problem comes when I click on one of the objects. Other models are fine. Working with the object in code (i.e. creating and displaying) is ok, the problem only arises when I try to view an object with the admin interface. The class isn't even particularly exotic:
class Comment(models.Model):
user = models.ForeignKey(User)
thing = models.ForeignKey(Thing)
date = models.DateTimeField(auto_now_add=True)
content = models.TextField(blank=True, null=True)
approved = models.BooleanField(default=True)
class Meta:
ordering = ['-date']
Any ideas? I'm stumped. The only reason I could think of might be that the thing
is quite a large object (a few kb), but as I understand it, it wouldn't get loaded until it was needed (correct?).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这实际上并不是
Thing
对象有多大的问题,而是数据库中有多少个对象的问题。这是因为对于外键,默认情况下 Django 的管理员会为您提供一个包含所有现有项目的下拉列表。如果你有很多很多,那么 Django 将加载它们全部以填充该列表。这里的User也是同样的情况。解决这个问题的最佳方法是将有问题的字段添加到 ModelAdmin 子类中的
raw_id_fields
中。这会将表示形式更改为 id 的简单文本字段,并带有弹出查找窗口。It's not really a question of how big the
Thing
object is, but rather of how many you have in your database. That's because for a ForeignKey, by default Django's admin gives you a drop-down list containing all the existing items. If you've got lots and lots, then Django will load them all in order to populate that list. The same is true here of User.The best way round this is to add the offending field to the
raw_id_fields
in your ModelAdmin subclass. That will change the representation to a simple textfield for the id, with a pop-up lookup window.