pythondjangodjango-modelsforeign-keysimport-from-csv

How to import a .csv table with a foreign key into a django database


This is my first Django project and I am having difficulty loading data from a .csv file into a model with a foreign key.

Here are my models:

class Artist(models.Model):
    artistID = models.IntegerField(primary_key=True, null=False, unique=True)
    artistName = models.CharField(max_length=50)
    artistNotes = models.TextField(blank=True)

class Art(models.Model):
    artID = models.IntegerField(primary_key=True, null=False, unique=True)
    artistID = models.ForeignKey(Artist, db_column='artistID', on_delete=models.CASCADE, default = 1)
    title = models.CharField(max_length=100, default = "No Title Given")
    location = models.CharField(max_length=100)
    owner = models.CharField(max_length=50, blank=True)
    origin = models.CharField(max_length=150, blank=True)
    medium = models.CharField(max_length=50, blank=True)
    artNotes = models.TextField(blank=True)

I wrote a view that would import the data:

def importArt(request):
    myFile = open('misc/Art.csv', 'r')
    for line in myFile:
        line = line.split(',')
        temp = Art.objects.create()
        temp.artID = line[0]
        temp.artistID = line[1]
        temp.title = line[2]
        temp.location = line[3]
        temp.owner = line[4]
        temp.origin = line[5]
        temp.medium = line[6]
        temp.artNotes = line[7]
        temp.save()
    myFile.close()
    return render(request, 'dtccArt/importArt.html', {})

This strategy worked fine for the Artist table but this is the error that I am getting: Cannot assign "'2'": "Art.artistID" must be a "Artist" instance.

My first line of data looks like this:

1,2,Wisdom & Knowledge,Main Library,College,Visiting Artist at DTCC 19??-19??,Stone Sculpture,,

I fixed two errors before getting to this stuck point. I added db_column='artistID' and default = 1 to the Art model's ArtistID field. The default = 1 refers to an unknown artist in case the artist is unknown for a piece of art.

Can someone explain what the error message means, some hints on how to fix it, or an easier way to import .csv data into an existing Django model?

Thanks in advance! Andrea


Solution

  • With Rakesh's help, I figured out how to do it. The following view works:

    def importArt(request):
        myFile = open('misc/Art.csv', 'r')
        for line in myFile:
            line = line.split(',')
            temp = Art.objects.create()
            temp.artID = line[0]
            if line[1] != '':
                temp.artistID = Artist.objects.get(pk = (line[1]))
            else:
                temp.artistID = Artist.objects.get(pk = 1)
            if line[2] != '':
                temp.title = line[2]
            else:
                temp.title = "Unknown"
            temp.location = line[3]
            temp.owner = line[4]
            temp.origin = line[5]
            temp.medium = line[6]
            temp.artNotes = line[7]
            temp.save()
        myFile.close()
        return render(request, 'dtccArt/importArt.html', {})
    

    The ArtistID and Title are required fields, so I hard-coded in "Unknown" for the missing Title. The PK = 1 artist has Unknown as its name.