【问题标题】:How to assign Foreign key inside loop Django如何在循环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'})

【问题讨论】:

    标签: python django django-models django-views


    【解决方案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'})
    

    【讨论】:

      猜你喜欢
      • 2011-04-10
      • 2013-09-28
      • 1970-01-01
      • 2021-10-20
      • 2015-08-30
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多