django-import-export: How to import data with foreign keys that doesn't have the keys, but the names?
Asked Answered
D

1

6

I am trying to set up django-import-export to handle my data which is stored in spreadsheets. The spreadsheets don't contain foreign keys as IDs, but rather they contain the (also unique) names of the correlating object. Within my database I will have foreign key relationships of Teachers who work at Schools which are located in Cities.

Imagine this to be the models (excerpt):

class School(models.Model):
    city = models.ForeignKey(City)
    name = models.CharField(max_length=200)


class Teacher(models.Model):
    school = models.ForeignKey(School)
    name = models.CharField(max_length=200)

The spreadsheet for teachers could look like this:

school,name
Central Grammar School,John Smith
West Primary,Jane Doe
West Primary,John Doe
...,...

How do I build the SchoolResource model so that during import it will accept the names instead of the IDs?

(I cannot just take the IDs from the database because the idea is, at one point, to start the database from scratch with only the spreadsheet data, which will not contain any IDs.)

Dowsabel answered 8/9, 2015 at 20:33 Comment(0)
N
8

ForeignKeyWidget accepts optional field argument, so it would looks like this in SchoolResource:

school = fields.Field(column_name='school',
                      attribute='school', 
                      widget=ForeignKeyWidget(School, 'name'))

See documentation for ForeignKeyWidget.

Norry answered 9/9, 2015 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.