tags:

views:

57

answers:

2

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?

+1  A: 

There's no way to save a foreign key without the object first existing in the database. Django needs to know the id assigned to the foreign object before it can reference it.

You could possibly abstract the code such that you won't see all the save(), but they will still have to occur before the object can be used as a foreign key.

Kai
+1  A: 

You can use the Model.objects.create method, which creates a new instance, saves it and returns a pointer to the new object, ready to define relationships to other instances.

#create a new Pizza
#There's no need to explicitly save the new Pizza instance
new_pizza = Pizza.objects.create(name='Canadian')

#Add Cities to Pizza
#Here, Toronto and Montreal are City instances you created earlier
#There's no need to save new_pizza after adding cities
new_pizza.cities.add(Toronto, Montreal)

#Create a new Price object for new_pizza
#There's no need to explicitly save new_pizza or the new Price instance.
new_pizza.price_set.create(usd=Decimal('8.99'),cad=Decimal('9.99'))

Note that by defining the pizza ForeignKey in the Price model, a Pizza can have more than one Price. Is this what you meant? Defining a price ForeignKey in Pizza would give one price per Pizza.

Alasdair