soultaker
soultaker

Reputation: 25

Calculate price in models with django v2.1

I need your help about this app I'm making, in those models, I want the price of the topping and the type be calculated automatic in the model Pizza, so when someone record new data, he can choice the type and the topping and the price is calculated and save it in that table Pizza.

class Type(models.Model):
 typeName = models.CharField( max_length = 50 )
 priceBase = models.DecimalField( max_digits = 6, decimal_places = 0, default=0 )
 obsBase = models.CharField( max_length = 200, null=True )

 def __str__(self):
    return self.typeName


class Topping(models.Model):
 nameTopping = models.CharField( max_length = 200)      
 priceTopping = models.DecimalField( max_digits = 6, decimal_places = 0, default=0 )
 obsTopping = models.CharField( max_length = 200, null=True )

 def __str__(self):
    return self.nameTopping


class Pizza(models.Model):
 namePizza = models.CharField(max_length=200)
 typePizza = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True )
 toppingPizza = models.ForeignKey(Topping, on_delete=models.SET_NULL, null=True)
 obsPizza = models.CharField(max_length = 200, null=True)

 def __str__(self):
    return self.namePizza

Guys, can I use this logic to save my kind of pizzas in a database so I can retrive the calculated data when someone order a pizza online?, I'm starting with the right foot?, sorry I'm new at django, and I'm trying to learn everything on the web, and your help will be precious for me! Thank You, have a nice day/night guys!

Upvotes: 0

Views: 423

Answers (1)

Sascha Rau
Sascha Rau

Reputation: 357

you can extend the save function

class Pizza(models.Model):
    namepizza = models.CharField(max_length=200)
    typepizza = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True)
    toppingpizza = models.ForeignKey(Topping, on_delete=models.SET_NULL, null=True)
    obspizza = models.CharField(max_length=200, null=True)
    pricetotal = models.DecimalField(max_digits=6, decimal_places=0, default=0)

    def save(self, *args, **kwargs):
        self.pricetotal = self.typePizza.priceBase + self.toppingPizza.priceTopping
        super(Pizza, self).save(*args, **kwargs)

    def __str__(self):
        return self.namepizza

in views.py use get_or_create()

Upvotes: 1

Related Questions