开发者

Django: one-to-many queries

开发者 https://www.devze.com 2023-04-12 03:22 出处:网络
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 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 rea开发者_如何学Clized 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号