Home > Software design >  How to insert value in a forign key from the csv file
How to insert value in a forign key from the csv file

Time:07-09

I want to insert the Matches and Delivery table from matches.csv and delivery.csv in the Django database. models.py looks like this:

from django.db import models

# Create your models here.
class Matches(models.Model):
    id=models.IntegerField(primary_key=True)
    season = models.IntegerField()
    city = models.CharField(max_length=200)
    date = models.DateField(null=True)
    team1 = models.CharField(max_length=200)
    team2 = models.CharField(max_length=200)
    toss_winner = models.CharField(max_length=200,null=True)
    toss_decision = models.CharField(max_length=200,null=True)
    result = models.CharField(max_length=200,null=True)
    dl_applied = models.CharField(max_length=200,null=True)
    winner = models.CharField(max_length=200,null=True)
    win_by_runs = models.IntegerField(null=True)
    win_by_wickets = models.IntegerField(null=True)
    player_of_match = models.CharField(max_length=200,null=True)
    venue = models.CharField(max_length=200,null=True)
    umpire1 = models.CharField(max_length=200,null=True)
    umpire2 = models.CharField(max_length=200,null=True)
    umpire3 = models.CharField(max_length=200,null=True)
    

class Deliveries(models.Model):
    match_id= models.ForeignKey(Matches,on_delete=models.CASCADE)
    inning = models.IntegerField()
    batting_team = models.CharField(max_length=100)
    bowling_team = models.CharField(max_length=100)
    over = models.IntegerField()
    ball = models.IntegerField()
    batsman = models.CharField(max_length=100)
    non_striker = models.CharField(max_length=100)
    bowler = models.CharField(max_length=100)
    is_super_over = models.IntegerField()
    wide_runs = models.IntegerField()
    bye_runs = models.IntegerField()
    legbye_runs = models.IntegerField()
    noball_runs = models.IntegerField()
    penalty_runs = models.IntegerField()
    batsman_runs = models.IntegerField()
    extra_runs = models.IntegerField()
    total_runs = models.IntegerField()
    player_dismissed = models.CharField(max_length=100)
    dismissal_kind = models.CharField(max_length=100)
    fielder =models.CharField(max_length=100)

I am updating this table using management/commands/updateModels.py and my updateModles.py looks like this:django

from django.core.management.base import BaseCommand
import csv

from match.models import Matches, Deliveries


class Command(BaseCommand):
    help = 'import booms'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        # database connections here
        with open('matches.csv') as f:
            match_obj = csv.DictReader(f)
            for match in match_obj:
                model=Matches(
                id=match['id'],
                season=match['season'],
                city=match['city'],
                date=match['date'],
                team1=match['team1'],
                team2=match['team2'],
                toss_winner=match['toss_winner'],
                toss_decision=match['toss_decision'],
                result=match['result'],
                dl_applied=match['dl_applied'],
                winner=match['winner'],
                win_by_runs=match['win_by_runs'],
                win_by_wickets=match['win_by_wickets'],
                player_of_match=match['player_of_match'],
                venue=match['venue'],
                umpire1=match['umpire1'],
                umpire2=match['umpire2'],
                umpire3=match['umpire3'])
                model.save()
        with open('deliveries.csv', 'r') as file:
            delivery_obj = csv.DictReader(file)
            for delivery in delivery_obj:
                model=Deliveries(
                match_id=delivery['match_id'],
                inning = delivery['inning'],
                batting_team =delivery['batting_team'] ,
                bowling_team = delivery['bowling_team'],
                over = delivery['over'],
                ball = delivery['ball'],
                batsman = delivery['batsman'],
                non_striker = delivery['non_striker'],
                bowler = delivery['bowler'],
                is_super_over = delivery['is_super_over'],
                wide_runs = delivery['wide_runs'],
                bye_runs = delivery['bye_runs'],
                legbye_runs = delivery['legbye_runs'],
                noball_runs = delivery['noball_runs'],
                penalty_runs = delivery['penalty_runs'],
                batsman_runs = delivery['batsman_runs'],
                extra_runs = delivery['extra_runs'],
                total_runs = delivery['total_runs'],
                player_dismissed = delivery['player_dismissed'],
                dismissal_kind = delivery['dismissal_kind'],
                fielder =   delivery['fielder'],)
                model.save()

With this Matches table is filled but in Delivery, not a single row is inserted instead this is the error given by Django:

Traceback (most recent call last):
  File "/home/dell/Desktop/d_ipl/ipl/manage.py", line 22, in <module>
    main()
  File "/home/dell/Desktop/d_ipl/ipl/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/dell/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/home/dell/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/dell/env/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/dell/env/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute
    output = self.handle(*args, **options)
  File "/home/dell/Desktop/d_ipl/ipl/match/management/commands/updateModels.py", line 41, in handle
    model=Deliveries(
  File "/home/dell/env/lib/python3.10/site-packages/django/db/models/base.py", line 541, in __init__
    _setattr(self, field.name, rel_obj)
  File "/home/dell/env/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 235, in __set__
    raise ValueError(
ValueError: Cannot assign "'1'": "Deliveries.match_id" must be a "Matches" instance.

CodePudding user response:

If you are not assigning a real object instance, you have to use the field name with the _id suffix. As you are already named your ForeignKey match_id, you have to use match_id_id to assign the ForeignKey value instead of the object.

        with open('deliveries.csv', 'r') as file:
            delivery_obj = csv.DictReader(file)
            for delivery in delivery_obj:
                model=Deliveries(
                match_id_id=delivery['match_id'],  # use the ForeignKey field with the '_id' suffix
                inning = delivery['inning'],
        # ... your code

https://docs.djangoproject.com/en/4.0/ref/models/fields/#database-representation

  • Related