ksiomelo
ksiomelo

Reputation: 1908

Saving nested models in Django-NoRel gives "can't encode" error

I can save a "Node", "Link" but not a "Graph" (see error below). Using pymongo 2.1.1, Django-NoRel, Python 2.7:

from django.db import models
from djangotoolbox.fields import SetField, ListField, EmbeddedModelField

class Graph(models.Model):
    links = ListField(EmbeddedModelField('Link'))

class Link(models.Model):
    parent = EmbeddedModelField('Node')
    child = EmbeddedModelField('Node')

class Node(models.Model):
    extent = SetField() # set of strings e.g. "Gene-Bmp4"
    intent = SetField() # set of strings

--

n1 = Node(extent=set(["Gene-bmp4"]),intent=set(["Attr1", "Attr2"]))
n2 = Node(extent=set(["Gene-fp4"]),intent=set(["Attr3", "Attr4"]))
link = Link(parent=n1, child=n2)
links = [link]
g = Graph(links=links)
g.save()

produces the error:

/Library/Python/2.7/site-packages/pymongo-2.1.1-py2.7-macosx-10.7-intel.egg/pymongo/collection.py:312: RuntimeWarning: couldn't encode - reloading python modules and trying again. if you see this without getting an InvalidDocument exception please see api.mongodb.org/python/current/faq.html#does-pymongo-work-with-mod-wsgi

Exception Type:     InvalidDocument
Exception Value:    Cannot encode object: set(['Attr2', 'Attr1'])
Exception Location:     /Library/Python/2.7/site-packages/pymongo-2.1.1-py2.7-macosx-10.7-intel.egg/pymongo/collection.py in insert, line 312

Does anyone has any idea what should I do??

Upvotes: 1

Views: 793

Answers (2)

Jonas H.
Jonas H.

Reputation: 2491

Looks like a bug to me. Please open a ticket at https://github.com/django-nonrel/djangotoolbox

Upvotes: 2

Kyle Banker
Kyle Banker

Reputation: 4359

The issue here is that you cannot encode an object of type 'set' as BSON since BSON has not 'set' type.

The best solution is to covert the set to an array before you go to save the graph.

Upvotes: 1

Related Questions