'How to convert JSON data in to python instance and save Django models multiple table with foreginkey (database sqllite)

I am not able to save with id_category = models.ForeignKey
please help me to solve

ValueError: Cannot assign "21": "Categories.parent" must be a "Parents" instance.

View.py

def GetProducts(request):  
    endpoint = "[https://myurl.net/products/][1]"
    response = requests.request("GET", endpoint)
    data = json.loads(response.text)
        
    for cat in data['Category']:
                        ›
            pro_cat = ProCatData(
                id=cat['id'],
                name=cat['name'],
                image=cat['image'],
            )
            pro_cat.save()
    
    for product in data['Products']:
        
            Products = ProductsData(
                id=product['id'],
                name=product['name'],
                id_category=product['id_category'],
                description=product['description'],
                image=product['image'],
            )
            Products.save()
        

model.py

class ProCatData(models.Model):
    
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30, null=True, blank=True)
    image = models.CharField(max_length=30)
    
 
    def __str__(self):
        return self.name
    
class ProductsData(models.Model):
    
    id_category = models.ForeignKey(ProCatData,    on_delete=models.DO_NOTHING,null=True, blank=True) 
    image = models.CharField(max_length=300, null=True, blank=True)
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=30, null=True, blank


Solution 1:[1]

If you are using the primary key of the object, it should be id_category_id, so:

for product in data['Products']:
    ProductsData.objects.create(
        id=product['id'],
        name=product['name'],
        id_category_id=product['id_category'],
        description=product['description'],
        image=product['image'],
    )

But it makes not much sense to give a ForeignKey an id_… prefix (or …_id suffix), since it will fetch the ProCatData record, not return the primary key of that object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem