Hibernate's component mapping type for Django
|Reported by:||anonymous||Owned by:||Adrian Holovaty|
|Component:||Database layer (models, ORM)||Version:|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Something similar to component mapping type of Hibernate (http://www.hibernate.org/hib_docs/v3/reference/en/html/components.html) would be a great addition to Django's model API.
Currently, the same behaviour can be achieved by using an one-to-one relation between two models, but 1) one-to-one isn't recommended, 2) it's a bit overkill for simple models. Let's say we have model Product. Naturally, we'd like to have a price for the product. To be as object-oriented as possible, we would like to model the price as MonetaryAmount, which would contain the following information: the amount of money and the currency it is in.
With one-to-one models, we could model this as follows:
class Product(models.Model): ... class MonetaryAmount(models.Model): money_amount = models.FloatField() currency = models.CharField() product = models.OneToOneField(Product)
This works, but as mentioned, it's a bit overkill: another table in database just to hold information about amount of money and the currency it is in and the need for extra-JOINs when retrieving database records.
With component mapping the fields introduced in MonetaryAmount would be mapped at database to the same table with Product and therefore no additional tables nor JOINs would be needed. This could be modeled, for example, as:
class MonetaryAmount(object): money_amount = models.FloatField() currency = models.CharField() class Product(models.Model): ... price = models.ComponentField(MonetaryAmount)