Django:一对多查询

发布于 2024-12-09 07:30:06 字数 581 浏览 1 评论 0原文

我的数据库结构中有很多一对多关系。例如,你有一个用户,该用户有很多学位,他有很多电子邮件,他有很多合同等等。

我在Django的查询集中发现了这个“select-lated()”功能,它看起来很棒。但是它不会“向后”,它仅在您开始使用的表具有所有其他表的外键时才有效,但如果它是一对多,您不会将所有外键存储在 user 中桌子。

所以我的问题是,有没有什么办法,我可以,

  1. 点击数据库一次,
  2. 仍然能够使用 Django 漂亮的面向对象模型,最好是像 user. Degree[0] .school_name 这样的东西 - 这会很棒。

任何帮助将不胜感激!

编辑1:嗯实际上我刚刚意识到,从技术上讲,用户表不包含任何字段名称学位。您知道学位与用户关联的唯一方法是浏览学位表并查找用户外键。所以在某种程度上,这有点像某种数据库视图...

编辑 2:我想您可以在数据库中创建一个包含大量 JOIN 的视图,并在 Django 中创建一个模型来镜像该视图,对吗?只是弄清楚所有不同的数据库如何处理视图上的 INSERT/UPDATE/DELETE 的问题...不确定是否有列表,我现在正在使用 postgresql。

I got a lot of one-to-many relationships in my database structure. For example, you have a user, the user has many degrees, he has many emails, he has many contracts, etc.

I found out about this "select-related()" feature in Django's queryset, it seems great. However it doesn't go "backwards", it only works when the table you're starting with has foreign keys to all the other tables, but if it's one-to-many you're not gonna store all the foreign keys in user table.

So my question is, is there some way that I can,

  1. Hit the database once
  2. Still be able to use Django's nice object-oriented model, ideally something like, user.degree[0].school_name - this would be awesome.

Any help would be greatly appreciated!!

Edit 1: hmm actually I just realized that, technically, the user table does NOT contain any fields name degree. The only way you'd know that a degree is associated with a user is going through the degree table and looking for user foreign keys. So in a way this is sort of like a database view of sorts...

Edit 2: I guess you could just create a view in the database with lots of JOINs and create a model in Django to mirror that view right? Just a matter of figuring out how all the different databases handle INSERT/UPDATE/DELETE on a view... not sure if there's a list, I'm using postgresql right now.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

无需解释 2024-12-16 07:30:06

您应该看看django-unjoinify,它允许您使用自己定制的优化 SQL,但允许您将结果映射到特定模型。

如果您采取创建数据库视图的方式(我自己创建了很多数据库视图,我认为这是一个好主意。)您可能应该覆盖模型的 save() delete()update() 和类似的方法来实际写入相应的表。

“针对您需要的所有内容触发一次查询,而不是为每条记录触发一次查询”确实是一种经典的数据库智慧。上述两种方法都有助于实现这一目标。

You should have a look at django-unjoinify that lets you use your own customized optimized SQL and yet allows you to map the result to a specific model.

If you take the route of creating a database-view, (I have created many myself and I think this is a good idea.) you should probably override the model's save() delete(), update() and similar methods to actually write to the respective tables.

It is indeed a classic database wisdom that "Fire one query for all that you need rather than one query per record". Both the approaches above help in achieving it.

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