我有以下型號:保存ManyToManyField和在Django
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)
我可以創建下面的代碼一個全新的比薩餅:
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()
我可能有一些錯字這裏但上面的工作很好,但我不喜歡這麼多次保存對象。有沒有更好的方法從上面的當前模型從頭創建一個Pizza對象?