Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading