Monday, May 18, 2020

Django foreign-key cannot assign must be a instance

Hi all, 

I am trying to add a row in the DB using the following views.py: 

# Create your views here.
from django.shortcuts import render
from fusioncharts.models import Component,Report
import xlrd
def pie_chart(request):
    labels = []
    data = []
    loc = ("C:\Django_apps\QRC_Report.xlsx")
    workbook = xlrd.open_workbook(loc) 
    worksheet = workbook.sheet_by_name('Sheet1')
    num_rows = worksheet.nrows - 1
    num_cols = worksheet.ncols - 1
    curr_row = -1
    component = []
    comp = None 
    while curr_row < num_rows:
      curr_row += 1
      row = worksheet.row(curr_row)
      curr_col = -1
      if "Header" in worksheet.cell_value(curr_row, 0):
        compon = worksheet.cell_value(curr_row, 0).strip("*")
        print("The component is %s" %compon)
        component.append(compon)
        print("===========The results of the component %s is as follows============" %compon)
        Component.objects.create(comp=compon)
        continue
      while curr_col < num_cols:
        curr_col += 1
        cell_value = worksheet.cell_value(curr_row, curr_col)    
        #print("Cell value = %s" %cell_value)
        test_name = worksheet.cell_value(curr_row,0)
        print("Test name = %s" %test_name)
        test_value = worksheet.cell_value(curr_row,1)
        print("Test result = %s" %test_value)
        print("The component is = %s" %comp)
        Report.objects.create(param=test_name,comp=compon,value=test_value)
    return render(request, 'pie_chart.html', {
        'labels': labels,
        'data': data,
    })

However the above highlighted line is throwing the following error: 
Cannot assign "'Header SQL Detailed'": "Report.comp" must be a "Component" instance.

My model is as follows: 

from django.db import models
from django.urls import reverse
from decimal import Decimal
# Create your models here.
class Component(models.Model):
    comp = models.CharField(max_length=30)
class Report(models.Model):
    comp = models.ForeignKey(Component,on_delete=models.CASCADE)
    param = models.CharField(max_length=30)
    value = models.DecimalField(max_digits=25,decimal_places=18,default=Decimal('0.0000'))


Can anyone please point out what is going wrong here? What should be the correction? 

Thanks. 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/afb5a06a-0d7d-4038-a0fc-3c2aadbbe4fc%40googlegroups.com.

No comments:

Post a Comment