Reputation: 5455
I am trying to use ModelField to serialize a JSONField. I am not quite sure what is the expected thing to be passed into 'model_field' kwarg. Passing the class name doesn't cut it since the ModelField seems to be storing the 'model_field' directly and calling methods on that.
== restapi.py ==
reading_order = ModelField(model_field=JSONField) # Corresponds to a JSONField 'reading_order' in my model.
== rest_framework/fields.py ModelField ==
def field_to_native(self, obj, field_name):
value = self.model_field._get_val_from_obj(obj)
This results in error saying that first argument should be an instance to JSONField which makes sense since self.model_field is the class definition. If I change it to:
def field_to_native(self, obj, field_name):
value = self.model_field._get_val_from_obj(obj._meta.get_field(field_name), obj)
It works fine.
I am not sure if this is a bug I have stumbled upon or if I am instantiating the ModelField wrong. Can someone please point me to right way to use ModelField?
Regards, Abhaya
Upvotes: 1
Views: 1610
Reputation: 33901
Believe that's a docs issue. ModelField
should be passed a field instance, not a field class, so you should instantiate the model field like so:
reading_order = ModelField(model_field=JSONField())
Upvotes: 1