Create() in Django gives me ValueError "Field 'width' expected a number but got 'NA'
I am trying to insert several rows from .csv file into SQLite in Django. I don't want to be using import_data(), because I wanted to have a more granular control for each insertion. My model is something like this:
class Box(models.Model):
name = models.CharField(max_length=30)
color = models.CharField(max_length=30)
size = LengthField(blank=True, null=True, default=None, decimal_places=2,validators=(MinValueValidator(0, field_type='Length'),MaxValueValidator(100, field_type='Length'))))
Only name has a constraint to be unique.
Now, when i am running get_or_create
, and have a csv row that has a blank for size, i am getting an error "ValueError - Field 'size' expected a number but got 'NA'". (For the csv rows before that, everything is inserted correctly.)
I find it strange because in the model i have blank=True
and null=True
for size. What could i be doing wrong and how i could fix that? Thank you in advance!
Well you try to pass the string 'NA'
as value for the size
field, hence that does not work. In the logic you use to create model objects, you should replace it with None
, so something similar to:
name = …
color = …
size = …
# ↓ replace 'NA' with None
if size == 'NA':
size = None
Box.objects.get_or_create(
name=name,
defaults={'color': color, 'size': size}
)