Gavin
Gavin

Reputation: 33

Django: posting to foreign keys results in matching query does not exist

Models:

class CompanyList(models.Model):
    company_id = models.CharField(max_length=10, unique=True)
    company_name = models.CharField(max_length=100, unique=True)


class Reporting(models.Model):
    company = models.ForeignKey(CompanyList, on_delete=models.CASCADE)
    year_end = models.DateField()


class CompanyAccountsExtracts(models.Model):
    reporting = models.ForeignKey(Reporting, on_delete=models.CASCADE)
    data_type = models.CharField(max_length=30)
    source = models.CharField(max_length=30)
    value = models.CharField(max_length=30)

Now I have a pandas dataframe (company_accounts_extracts_upload) of data to write to CompanyAccountsExtracts. I am using the following code to do so:

for i, row in enumerate(company_accounts_extracts_upload.values):

    single_row = company_accounts_extracts_upload.iloc[i].to_dict()

    report = models.Reporting.objects.get(company=single_row['Company ID Number'], year_end=single_row['Year End'])

    DataExtract = models.CompanyAccountsExtracts(reporting=report,
                                             data_type=single_row['DataType'],
                                             source=single_row['Source'],
                                             value=single_row['Value'],
                                             )
DataExtract.save()

I am getting the following error on the "report = models.Reporting..." line:

DoesNotExist: Reporting matching query does not exist.

However, I'm 100% sure the company and year end does exist as I can see it in the admin view.

I think the error might be related to how I am posting to a foreign key as the Reporting foreign key which again is a foreign key from CompanyList?

Upvotes: 1

Views: 821

Answers (1)

Marcell Erasmus
Marcell Erasmus

Reputation: 914

You need to update your company query param from:

company=['Company ID Number']

to:

company__company_id=['Company ID Number']

You are getting the error because the company param will need a Company instance and you are only using the company_id field.

Upvotes: 1

Related Questions