user8318311
user8318311

Reputation:

Value Error when assign to foreign key field while creating the object

I have the following Models

from django.db import models 


class League(models.Model):
    league_id = models.IntegerField()
    country = models.ForeignKey('Country', on_delete = models.CASCADE)
    name = models.CharField(max_length = 50)
    logo = models.CharField(max_length = 250)
    season = models.IntegerField()
    season_start = models.DateField()
    season_end = models.DateField()
    standings = models.BooleanField(default= False)




class Country(models.Model):
    country = models.CharField(max_length = 20, primary_key=True)
    country_id = models.IntegerField()

I created custom management command to get data from API then extract disered data from API responce and create object of model based on this data. My custom management command code

from django.core.management.base import BaseCommand, CommandError 
from data.models import League, Country  
import requests 
import json 




def extracting_league():
    response = requests.get("https://api-football-v1.p.rapidapi.com/leagues", headers={"X-RapidAPI-Key": "rRVyARf9ESmshWSiNIkYcTr0jp1nQh2JjsnNGNlcEYXM1XI"})
    league = json.loads(response.text)
    return league 

parsed_league = extracting_league() 
print(parsed_league)

def pars():
    leagues = parsed_league['api']['leagues']
    for id in parsed_league['api']['leagues']:
        lg_id = leagues[id]["league_id"]
        lg_name = leagues[id]["name"]
        lg_country = Country.objects.get_or_create(country = leagues[id]["country"])
        lg_logo = leagues[id]["logo"] 
        lg_season = leagues[id]["season"]
        One_league = League.objects.create(league_id = lg_id, country = lg_country, name = lg_name, logo = lg_logo, season = leagues[id]["season"], season_start = leagues[id]["season_start"], season_end = leagues[id]["season_end"], standings = leagues[id]["standings"]) 
        One_league.save()
        print(One_league)


class Command(BaseCommand):
    def handle(self, **options):
        extracting_league()
        pars() 

When i run script with python manage.py 'custom management commmand' i see in console the following error notifications

 Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\extract_league.py", line 70, in handle
    pars()
  File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\extract_league.py", line 25, in pars
    One_league = League.objects.create(league_id = lg_id, country = lg_country,
name = lg_name, logo = lg_logo, season = leagues[id]["season"], season_start = l
eagues[id]["season_start"], season_end = leagues[id]["season_end"], standings =
leagues[id]["standings"])
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 411, in create
    obj = self.model(**kwargs)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 467, in __init__
    _setattr(self, field.name, rel_obj)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\fields
\related_descriptors.py", line 210, in __set__
    self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "(<Country: Country object (Turkey)>, False)": "League
.country" must be a "Country" instance.

I can not to understand the following traceback message

ValueError: Cannot assign "(<Country: Country object (Turkey)>, False)": "League
.country" must be a "Country" instance. 

It seems like in my Country model table is not country by Turkey name but when i look at table in PGadmin i have Turkey country in the Country table. Any suggestions

Upvotes: 0

Views: 388

Answers (1)

user8060120
user8060120

Reputation:

The django method get_or_create returns a tuple of (object, created), so you can use next solution:

lg_country, _ = Country.objects.get_or_create(country = leagues[id]["country"])

Upvotes: 3

Related Questions