pythondjangocsvdjango-modelsdjango-management-command

Django. Error writing database from csv via custom commands


I want to write my own command to quickly get data from csv. The script successfully fills the table User, Category, Genre. But when it comes to the Title model, I get the error ValueError: Cannot assign '1': 'Title.category' must be an instance of 'Category'. How to make beautiful without using additional modules?

models = {
    User: 'users.csv',
    Category: 'category.csv',
    Genre: 'genre.csv',
    Title: 'titles.csv',
}


class Command(BaseCommand):
    help = 'Command to automatically populate the database'

    def handle(self, *args, **options):
        path = str(BASE_DIR / 'static/data/')
        for model, csv_file in models.items():
            with open(path + '/' + csv_file, 'r', encoding='utf-8') as file:
                rows = csv.DictReader(file)
                records = [model(**row) for row in rows]                   
                model.objects.bulk_create(records)
            self.stdout.write(self.style.SUCCESS(f'Done {model.__name__})'))

Example CSV files:

  1. users.csv
id,username,email,role,bio,first_name,last_name
100,bingobongo,bingobongo@mail.fake,user
  1. category.csv
id,name,slug
1,Movie,movie
  1. genre.csv
id,name,slug
1,Drama,drama
  1. titles.csv
id,name,year,category
1,The Shawshank Redemption,1994,1

Solution

  • in your csv, rename the header category to be category_id