Last active
March 3, 2017 17:04
-
-
Save domibarton/3a4ac3a451252cc14cc8bf134f3eddc9 to your computer and use it in GitHub Desktop.
UnicodeError w/ Django, MySQL & custom unicode classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import absolute_import, unicode_literals | |
from django.db.models import TextField | |
class KeyValue(unicode): | |
pass | |
class KeyValueField(TextField): | |
def from_db_value(self, value, expression, connection, context): | |
return KeyValue(value) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import absolute_import, unicode_literals | |
from django.db import models | |
from keyvalue import KeyValueField | |
class MyFirstModel(models.Model): | |
value1 = models.TextField(default='', blank=True) | |
value2 = KeyValueField(default='', blank=True) | |
class MySecondModel(models.Model): | |
value1 = models.TextField(default='', blank=True) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import absolute_import, unicode_literals | |
from .models import MyFirstModel | |
MyFirstModel.objects.create( | |
value1="Hellö", | |
value2="Hellö", | |
) | |
MySecondModel.objects.create( | |
value="Test", | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import absolute_import, unicode_literals | |
from .models import MyFirstModel, MySecondModel | |
first = MyFirstModel.objects.get(id=1) | |
second = MySecondModel.objects.get(id=1) | |
second.value = first.value1 | |
second.save() # All fine! | |
second.value = first.value2 | |
second.save() # UnicodeError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment