5

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 database queryset response, I am getting the data field as Unicode and not as dict.

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

Am I missing out on something?

Shubham
  • 3,071
  • 3
  • 29
  • 46

1 Answers1

0

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

The QuerySet returned when using values returns items as dictionary instances (with each key corresponding to a requested column of the model) rather than Model instances (see doc). The values in the dictionary correspond to what is stored in the database, there is no complex object conversion from the data to the given field, as there is no instantiation of the model.

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

See:

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
...

versus

for a in SubmittedAnswer.objects.values('option_ids'):
  print a['option_ids']
>>> u'{"option_ids": [3]}' # unicode string as stored in database
...
rparent
  • 630
  • 7
  • 14