Django:一对多查询
我的数据库结构中有很多一对多关系。例如,你有一个用户,该用户有很多学位,他有很多电子邮件,他有很多合同等等。
我在Django的查询集中发现了这个“select-lated()”功能,它看起来很棒。但是它不会“向后”,它仅在您开始使用的表具有所有其他表的外键时才有效,但如果它是一对多,您不会将所有外键存储在 user 中桌子。
所以我的问题是,有没有什么办法,我可以,
- 点击数据库一次,
- 仍然能够使用 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,
- Hit the database once
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该看看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.