DjangoModelFactory JsonField returns Unicode data instead of dictionary data

I am trying to set a field of type JSONField using factoryboy DjangoModelFactory . Here is the code:

 class SubmittedAnswer(models.Model): data = JSONField(default={}) is_rule_check_passed = models.NullBooleanField() class SubmittedAnswerFactory(DjangoModelFactory): class Meta: model = SubmittedAnswer data = {"option_ids": [1]} 

In response to the database query request, I get the data field as Unicode , and not as a dict .

 'data': u'{"option_ids":[3]}'}] 

Am I missing something?

+5
source share
1 answer

My guess (based on the format of the output you output) is that you execute the query using values(...) .

The returned QuerySet when using values returns elements in the form of dictionary instances (with each key corresponding to the requested model column), rather than model instances (see doc ). The values ​​in the dictionary correspond to what is stored in the database; there is no complicated conversion of an object from data to a given field, since there is no model instance.

If you want to directly get model instances, use a regular QuerySet , for example. SubmittedAnswerFactory.objects.filter(...) . And if you want to select only some fields when executing the actual SQL query for optimization and still get model instances, use only (or defer ) instead of values (see doc ).

Cm:

 for a in SubmittedAnswer.objects.only('option_ids'): print a.option_ids >>> {'option_ids': [3]} # Dictionary object obtained by deserializing the data stored in the databse ... 

vs

 for a in SubmittedAnswer.objects.values('option_ids'): print a['option_ids'] >>> u'{"option_ids": [3]}' # unicode string as stored in database ... 
0
source

All Articles