views:

243

answers:

2

For the following models:

class Price:
    cad = models.DecimalField(max_digits=8, decimal_places=2)
    usd = models.DecimalField(max_digits=8, decimal_places=2)

class Product:
    name = models.CharField(max_length=255)
    price = models.ForeignKey(Price)

For each product, it's related to one and only one Price object which will contain either a Canadian or US dollar value. Is the above the proper way of doing setting that relationship? Here are some sample data:

Shirt, $100 US, $120 CAD
Book, $20 US, $25 CAD

I also want to input the above information from the admin so that interface will be similar to the following:

Add a Product:

  • name:
  • CAD:
  • USD:

I can more or less do the above with the following code:

class ProductInline(admin.StackedInline):
    model = Product

class PriceAdmin(admin.ModelAdmin):
    inlines = [
        ProductInline,
    ]

Am I doing it the proper way?

+1  A: 

Why not just make the fields cad and usd be members of the Product table? That way you get the admin goodness for free. What do you gain by them being stored in a separate model?

Also, why not just store just one price, and have an exchange rate (I don't know if that fits your pricing model, but it seems to from the example you gave). That way you'd just need to enter one price, and other bits of your system could display the price in an alternate currency if needed.

I do a similar thing with a template tag to manage the display of monetary values in a given currency according to a session variable (see the question I asked when I got stuck).

Dominic Rodger
I prefer the cad and usd being part of the Product table but according to other team members there might additional operations on the price itself such as discounts and so on.
Thierry Lam
But if there's a one-to-one correlation between prices and products, how would them being in separate tables help? What could you do with separate tables that you can't do with a single table?
Dominic Rodger
A: 

I think you have to use one2one relationships

class Price:
    cad = models.DecimalField(max_digits=8, decimal_places=2)
    usd = models.DecimalField(max_digits=8, decimal_places=2)

class Product:
    name = models.CharField(max_length=255)
    price = models. OneToOneField(Price, primary_key=True)

http://www.djangoproject.com/documentation/models/one%5Fto%5Fone/

panchicore