如何在循环Django中分配外键
Posted
技术标签:
【中文标题】如何在循环Django中分配外键【英文标题】:How to assign Foreign key inside loop Django 【发布时间】:2022-01-17 11:41:20 【问题描述】:我想为循环中的每种颜色分配一个外键
colorArray=[color:'red', product_id:5, color:'yellow', product_id:5]
产品型号
class Product(models.Model):
name = models.CharField(max_length=500)
brand = models.CharField(max_length=500)
description = models.CharField(max_length=500)
颜色模型
class Color(models.Model):
colorName = models.CharField(max_length=500)
product_id = models.ForeignKey(Product, on_delete=models.CASCADE)
观看次数
class AddColors(APIView):
def post(self,request):
for i in colorArray:
s=AddColors()
s.colorName=i['color']
s.product_id=i[Product.objects.get(id=i['product_id'])]
s.save()
return Response('colors Saved')
【问题讨论】:
【参考方案1】:在你看来你做错了:
class AddColors(APIView):
def post(self,request):
for i in colorArray:
s = AddColors() # This is not correct
s = Color() # Your model class is Color not AddColors
s.colorName = i['color']
# This is also incorrect:
s.product_id = i[Product.objects.get(id=i['product_id'])]
# It should be like this:
s.product_id = Product.objects.get(id=i['product_id'])
s.save()
return Response('colors Saved')
【讨论】:
以上是关于如何在循环Django中分配外键的主要内容,如果未能解决你的问题,请参考以下文章