开发者

django models question

I am working on a django model and not being a database expert I could use some advice. I essentially have a model which contains a many to many relationship with another model. But I need to store unique values for each relationship each time I include something.

So for instance in chemistry you may have many elements that include hydrogen, but each element has a unique amount of hydrogen in it. So开发者_Python百科 for instance a water entry would be connected to hydrogen and oxygen and the amount would be two hydrogen atoms and one oxygen.

I want hydrogen and water in this scenario to be stored in the database as elements, so I can query against them for other elements using them.

What is the best way to model this?

Thanks!


Read the documentaion here and pay close attention to the Beatles example, it's exactly what you need.

Person -> Element

Group -> Chemical_Compound

Membership -> Element_2_Chemical

Element_2_Chemical should have an int field which details how many elements you have in each chemical compound.


In your metaphor, you say "I want hydrogen and water in this scenario to be stored in the database as elements, so I can query against them for other elements using them."

Does it mean that "water" may be on any part of the relationship you are modeling? Do "water" relate to "hydrogen" in the (almost) same way as "milk" relates to "water"?

If the answer is Yes, then you should use a directed-acyclic-graph model (hopefully, you won't have cycles in your relationship: A->B->C->A). Look into the django-dag ( http://pypi.python.org/pypi/django-dag/ ) and django-treebeard-dag ( http://pypi.python.org/pypi/django-treebeard-dag/0.2 ) packages.

If the answer in No, so yo have a clear distinction between what's a "container" and what's a "containee", use a normal many-to-many rel between two different models, like the "Membership" example in django documentation ( https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships ).

In any case you'll have to add more info to the "edge" of the relationship.

Following strictly your chemical metaphor, you are maybe not modeling enough information, because some molecules have the same composition but different structure (they are called "isomers"). For instance the pentane, the 2-methylbutane and the 2,2-dimethylpropane have all five carbons and twelve hydrogens, but they are very different one another...

With this I am saying that when you are doing an "enhanced many-to-many" it's generally a complex model, so take care of not leaving anything out of it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜