'Django import-export how to handle blank Charfield
I'm trying to import some data with django import-export module. I'm having a problem and can't find any solutions to it despite the fact that it seems to be a very basic use of the import...
I'm trying to import some CharFields. These fields are not mendatory and as recommended by Django community, they are defined with blank=True in my model but not null=True.
Example:
description = models.CharField(max_length=2000, blank=True )
The problem is simple: When I try to import this field with an empty value, I get the error "NOT NULL constraint failed" on that field.
I don't understand how to solve this. Should I add null=True even if it's not usually recommended? Is there an option I don't know about?
Thanks for your help.
Solution 1:[1]
As you say, the Django docs state that you should avoid setting null on CharField.
django-import-export
should correctly handle persisting an empty string. However, we have seen that when importing from Excel, empty cells can be treated as None
.
To get around this, you can declare a Field
and add a default empty string and this should mean that Null / empty values are persisted as empty strings:
# adding 'default' will force empty values to be persisted as empty strings
book_id = fields.Field(attribute="book_id", column_name="id",
widget=widgets.CharWidget(), default="")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |