Skip to content Skip to sidebar Skip to footer

Assigning Data To Django Model From CSV From Iterator

I'm reading info in from a CSV to my django model, but it keeps throwing an ValueError: Cannot assign ''Sheffield United'': 'Match.home_team' must be a 'Team' instance. I can add d

Solution 1:

Since home_team is a ForeignKey, it can only accept instances of that model; you are trying to pass it a string which is the name of the home team, that's what this error means:

ValueError: Cannot assign "'Sheffield United'": "Match.home_team" must be a "Team" instance.

In your importer script, you need to search for the object that represents the home team, and assign that as the foreign key. You can use get_or_create to either fetch an existing team, or create a new team for the team name; like this:

from django.core.management.base import BaseCommand, CommandError
import csv
import csvImporter
from core.models import Match

master_data = open ('/Users/chris/Dropbox/Django/gmblnew/data/testfile.csv', 'r') 
data = list(tuple(rec) for rec in csv.reader(master_data, delimiter=','))
from core.models import Match, League, Team

for row in data:
    league, _ = League.objects.get_or_create(name=row[0])
    home_team, _ = Team.objects.get_or_create(team_name=row[2], league=league)
    away_team, _ = Team.objects.get_or_create(team_name=row[3], league=league)
    current_match = Match(
        league = league,
        home_team = home_team,
        away_team = away_team,
        match_date = row[1], 
        full_time_home_goals = row[4],
        full_time_away_goals = row[5],
        home_shots = row[10],
        away_shots = row[11],
        home_shots_on_target = row[12],
        away_shots_on_target = row[13],
        home_corners = row[16],
        away_corners = row[17],
        full_time_result = row[6],
    )
    print current_match

This line Team.objects.get_or_create(team_name=row[2]) means:

"Try to get a Team object whose team_name is the same as the value for row[2], if it doesn't exist, create a new Team object and return it instead"

get_or_create will return a 2-tuple, and the second part is a boolean to tell you if a new item was created or an existing item retrieved. Since we are only interested in the first part, I updated the code to only use the instance and ignore the second value.


Solution 2:

Try home_team = Team.objects.get(team_name=row[2]). The problem comes from the fact that the Team.id field is an integer field (since no primary_key field has been defined, django automatically creates an integer id field) and you are assigning a string to it.


Post a Comment for "Assigning Data To Django Model From CSV From Iterator"