0

Everything works great until the ObjectID value of the ReferenceField no longer points to a valid document. Then The ObjectID is left as the value, and json doesn't know how to serialize this.

How do I deal with invalid ReferenceFields?

E.g.

class Food(Document):
    name = StringField()
    owner = ReferenceField("Person")

class Person(Document):
    first_name = StringField()
    last_name = StringField()
    ...


p = Person(...)
apple = Food(name="apple", owner=p)
p.delete() # might be the wrong method, but you get the idea

At this point, attempting to fetch a list of foods via the REST API will fail with the is not JSON serializable error, since apple.owner no longer points to an owner that exists.

d0c_s4vage
  • 3,947
  • 6
  • 23
  • 32

1 Answers1

1

Since you are using DRF with mongoengine, you must be using django-rest-framework-mongoengine.

Apparenly, its a bug in django-rest-framework-mongoengine. Check this open issue on Github which was reported recently regarding the same.

https://github.com/umutbozkurt/django-rest-framework-mongoengine/issues/91

One way is to write your own JSONEncoder for this. This link might help.

Another option is to use the json_util library of Pymongo. They provide explicit BSON conversion to and from json.

As per json-util docs:

This module provides two helper methods dumps and loads that wrap the native json methods and provide explicit BSON conversion to and from json. This allows for specialized encoding and decoding of BSON documents into Mongo Extended JSON‘s Strict mode. This lets you encode / decode BSON documents to JSON even when they use special BSON types.

Community
  • 1
  • 1
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
  • Creating your own `JSONEncoder` might help. Check this ans. http://stackoverflow.com/a/16586277/4921103 – Rahul Gupta Aug 07 '15 at 14:38
  • Hrmm, I'll look at that. Thanks! – d0c_s4vage Aug 07 '15 at 14:39
  • Also, another option is the [`json_util`](http://api.mongodb.org/python/current/api/bson/json_util.html#module-bson.json_util) library in [`Pymongo`](http://api.mongodb.org/python/current/index.html#pymongo-release-documentation). They provide explicit `BSON` conversion to and from `json`. – Rahul Gupta Aug 07 '15 at 14:45
  • yeah, json_util is what I generally use for that. It's more I'm not sure where to tie that in/what to override in django-rest-framework-mongoengine to make it work. – d0c_s4vage Aug 07 '15 at 14:49
  • I think you can do that by creating your `CustomJSONRenderer` and then defining it as default renderer in your views or in the project's settings. – Rahul Gupta Aug 07 '15 at 14:56