开发者

one to many relations

I have 2 models and i want ,any instances on class 1 in class 2 how do i do it in django models ...and i tried using manytomany field but the problem is when i add a new object it will have that manytomany field al开发者_如何学编程ready there (which i dont want ) ...any idea how do i do this ...


A one to many relation is just a ForeignKey in the other direction.


One reason you may be having problems is relationships are somewhat backwards in relational databases from what they are in objects. It sounds like you want one instance of class2 to contain a list of class1. The way you do that is to have a ForeignKey on class1 that references class2. If you're not familiar with relational databases it'll seem like class2 should reference class1, but in the relational world, when you have a One-To-Many, the many need to reference the single.

For example say you have a folder structure. The "normal" way you'd think about it is that you have a folder, and that folder has some files in it. But in a relational database, the folder doesn't have a list of files. In fact nothing can (directly) have a list of anything else. What you do is then each file would know the id of the folder they're in. Now when you have a folder and you want to find the files that are in it, what you do is look at all the files and find the ones that have that folder as it's container.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜