How to assign Foreign key inside loop Django

enter image description hereI want assign foreign key to each colors in loop

colorArray=[{color:'red', product_id:5}, {color:'yellow', product_id:5}]

Product Model

class Product(models.Model):
    name = models.CharField(max_length=500)
    brand = models.CharField(max_length=500)
    description = models.CharField(max_length=500)

Color Model

class Color(models.Model):
    colorName = models.CharField(max_length=500)
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)

views

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'})

You are doing it the wrong way in your view:

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'})
Back to Top