dease
dease

Reputation: 3076

Insert CSV data in django models, empty values

I have CSV data which I add as django models each line after another.

for row in reader:
    elm, created_elm = Elm.objects.get_or_create(name=row[0], year=int(row[1]), power=int(row[2]))

Unlucky, in some cases row[1] is empty (in example, when csv row looks like:

Name,,1300

I get error

ValueError: invalid literal for int() with base 10: ''

How can I convert '' value to int 0 and then insert it to the database?

Upvotes: 1

Views: 332

Answers (2)

dease
dease

Reputation: 3076

I've googled and it may be even shorter:

year = row[1] or 0

We can close the question.

Upvotes: 2

sundar nataraj
sundar nataraj

Reputation: 8692

just give year=int(row[1]) if row[1] else 0

elm, created_elm = Elm.objects.get_or_create(name=row[0], year=int(row[1]) if row[1] else 0, power=int(row[2]))

Upvotes: 0

Related Questions