Home > Net >  Importing CSV file with NULL values to Django Models
Importing CSV file with NULL values to Django Models

Time:04-19

I'm importing csv files into Django models using a BaseCommand as such: load_data.py

import csv
from django.core.management import BaseCommand
from api.models import Location, LocationData

class Command(BaseCommand):
    help = "Load data from csv file into database"

    def add_arguments(self, parser):
        parser.add_argument('--path', type=str)

    def handle(self, *args, **kwargs):
        path = kwargs['path']
        with open(path, 'rt') as f:
            reader = csv.reader(f, dialect="excel")
            next(reader, None)
            for row in reader:
                LocationData.objects.create(
                    location = Location.objects.get(name=row[1]),
                    date = row[2],
                    hour = row[3],
                    measurement = row[4] if row[4] else None
                )

The measurement column has empty/NULL values so I set up the models.py as such:

class LocationData(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE)
    date = models.DateField()
    hour = models.PositiveSmallIntegerField(
        validators=[
            MinValueValidator(0),
            MaxValueValidator(24)
        ],
    )
    measurement = models.FloatField(default=None, null=True, blank=True)

    def __str__(self):
        return self.name

However, when I try to use the load_data.py which I have created, it resulted in an error:

django.db.utils.IntegrityError: NOT NULL constraint failed: api_locationdata.measurement

What I have tried: Deleting my migrations files and remigrating using python manage.py makemigrations but the error still occurs. What am I missing here?

Solution

I deleted the db and created a new one since my database is still empty.

CodePudding user response:

I assume you did the migrate after the makemigrations ? Youre db is out of sync, probably after deleting the migration files. If you have no data, create the db again and to the migrations stuff. Otherwise you have to do i manually

  • Related