I have the following models:
class City(models.Model):
name = models.CharField(max_length=100)
class Pizza(models.Model):
name = models.CharField(max_length=100)
cities = models.ManyToManyField('City')
class Price(models.Model):
cad = models.DecimalField()
usd = models.DecimalField()
pizza = models.ForeignKey(Pizza)
I can create a brand new pizza with the following code:
new_pizza = Pizza(name='Canadian')
new_pizza.save()
# I already calculated the following before, the syntax might not
# be correct but that's how you see it from the shell
new_pizza.cities = [<City: Toronto>, <City: Montreal>]
new_pizza.save()
new_price = Price(cad=Decimal('9.99'), usd=Decimal('8.99'), pizza=new_pizza.id)
new_price.save()
I might have some typo here and there but the above works fine but I just don’t like saving the objects so many times. Is there a better way to create a Pizza object from scratch with the current models above?
You can use the
Model.objects.createmethod, which creates a new instance, saves it and returns a pointer to the new object, ready to define relationships to other instances.Note that by defining the pizza ForeignKey in the
Pricemodel, aPizzacan have more than onePrice. Is this what you meant? Defining a price ForeignKey inPizzawould give one price per Pizza.