创建对象时分配给外键字段时出现值错误

时间:2019-02-27 15:33:56

标签: django django-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()

我创建了自定义管理命令,以从API获取数据,然后从API响应中提取错误的数据,并基于此数据创建模型对象。我的自定义管理命令代码

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() 

当我使用python manage.py'custom management commmand'运行脚本时,我在控制台中看到以下错误通知

 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.

我无法理解以下回溯消息

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

似乎在我的“国家/地区”模型表中不是按土耳其名字命名的国家/地区,但是当我在PGadmin中查看表格时,“国家/地区”表中有土耳其国家/地区。任何建议

1 个答案:

答案 0 :(得分:3)

django方法get_or_create返回一个(已创建对象)元组,因此您可以使用下一个解决方案:

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