我是Django的新手。我尝试从字典中创建我的两个模型披萨和浇头的几个实例:
dictionary = dict()
dictionary[“Pizza1”] = (“A”,”B”,”C”)
dictionary[“Pizza2”] = ()
dictionary[“Pizza3”] = (“B”,”D”)
我想将它们与ManyToMany关系联系起来,所以Pizza1有A,B,C配料,但Topping B也可以在Pizza 1和3中。我的代码不是以某种方式工作,它给了我三个披萨实例(Pizza1, 2,3)但都有所有浇头(A,B,C,D)而不是只有相应的浇头。我该怎么办呢?谢谢!
for pizza in dictionary:
pizza_instance, created1 = Pizza.objects.get_or_create(name=pizza)
if (len(dictionary[pizza])>0):
for topping in dictionary[pizza]:
topping_instance, created2 = Topping.objects.get_or_create(name=topping)
pizza_instance.has_toppings.add(topping_instance)
pizza_instance.save()
模型:
class Topping (models.Model):
name = models.CharField(max_length=20)
class Pizza (models.Model):
name = models.CharField (max_length=20)
has_toppings = models.ManyToManyField(Topping)
答案 0 :(得分:1)
试试这个,对我有用:
for pizza in dictionary:
pizza_instance, created1 = Pizza.objects.get_or_create(name=pizza)
for topping in dictionary[pizza]:
topping_instance, created2 = Topping.objects.get_or_create(name=topping)
pizza_instance.has_toppings.add(topping_instance)
pizza_instance.save()
测试:
>>> for p in Pizza.objects.all():
... print(p.has_toppings.count())
...
3
0
2