Django:在更改列表中显示多对多字段
Django 不支持在更改列表中显示多对多关系中的相关对象是有充分理由的。这将导致大量数据库命中。
但有时,不可避免且有必要在变更列表中显示与该对象具有多对多关系的对象类别。鉴于这种情况,是否有人有一些经验/片段等来加快速度(考虑缓存、自定义 sql 查询...)? (我知道我可以创建一个调用 object.categories.all()
的方法...但这真的很痛苦...)。
Django doesn't support displaying of related objects from a many-to-many relation in the changelist for a good reason. It would result in a lot of database hits.
But sometimes it is inevitable and necessary to e.g. display an object's categories, which have a many-to-many relation to the object, in the changelist. Given that case, does anybody have some experiences/snippets etc. to speed this up a little (thinking of caching, custom sql queries...)? (I am aware of the fact that I can make a method that calls object.categories.all()
... But this can really be a pain in the ass...).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您认为更改列表中的每行多一个数据库命中是不可接受的,那么您必须在模型中对
非规范化
做出选择。问题是如何存储这个ManyToMany关系?也许您可以使用同步的
JSON
序列化CharField
或TextField
中的对象,用于序列化所需字段的子集(pk
和name
例如)。但在添加潜在的大列时要小心对性能的副作用,查询集的 延迟方法是你的朋友。
Here you have to make a choice about
denormalization
in your model if you think that one more database hit per row in your changelist is unacceptable.The question is how to store this ManyToMany relation ? Maybe you can go with a synced
JSON
serialized object in aCharField
or aTextField
to serialize the subset of fields you need (pk
andname
for instance).But be careful with the side effects on performances when adding a potentially big column, the queryset's defer method is your friend.