Django:在更改列表中显示多对多字段

发布于 2024-09-26 04:27:58 字数 218 浏览 1 评论 0原文

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 技术交流群。

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

发布评论

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

评论(1

掐死时间 2024-10-03 04:27:58

如果您认为更改列表中的每行多一个数据库命中是不可接受的,那么您必须在模型中对非规范化做出选择。

问题是如何存储这个ManyToMany关系?也许您可以使用同步的 JSON 序列化CharFieldTextField 中的对象,用于序列化所需字段的子集(pkname 例如)。

但在添加潜在的大列时要小心对性能的副作用,查询集的 延迟方法是你的朋友。

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 a CharField or a TextField to serialize the subset of fields you need (pk and name 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.

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