Reputation: 107102
django fetches CharField
fields as unicode
, whereas sometimes str
is required. It is inefficient and tedious to write code that loops over the fields, checks the type and if it is unicode
casts it to str
.
Is there already a feature that can handle it?
If not what would be the most elegant way to handle this?
Upvotes: 1
Views: 604
Reputation: 53679
You can subclass the models.CharField class and override the to_python method:
from django.utils.encoding import smart_str
from django.db.models import CharField
class ByteStringField(CharField):
def to_python(self, value):
if isinstance(value, str) or value is None:
return value
return smart_str(value)
smart_str is the equivalent for bytestrings of the smart_unicode function normally used in CharFields.
EDIT: As Jonathan says, if you're using South, remember to extend south's introspection rules.
Upvotes: 1