Django model in one to one relationship and displaying it from admin

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 refers to one and only one Price object, which will contain the Canadian or dollar value. Is the above way of setting up a relationship? Here are some sample data:

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

      

I also want to enter the above information from the administrator, so the interface looks like the following:

Add product:

  • Name:
  • CAD:
  • USD:

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

class ProductInline(admin.StackedInline):
    model = Product

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

      

Am I doing it right?

+2


source to share


2 answers


I think you need to use one2one relationship

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_to_one/

0


source


Why not just turn on the field cad

and usd

in the table Product

? Thus, you get a free admin area. What do you get from them in a separate model?

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



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

+1


source







All Articles