Search code examples
pythondjangomongodbdjango-nonrel

Cannot query using IDs - Django MongoDB Engine


I am using django-nonrel and django-mongodb-engine

I have a Django model stored on PostgreSQL:

class Author(models.Model):
    name = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)

I have a MongoDB stored model:

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    author = models.ForeignKey(Author)

Whenever I try to filter posts by author id:

posts = Post.objects.filter(author__id=1)

I get the following error:

/usr/local/lib/python2.6/dist-packages/bson/objectid.pyc in __validate(self, oid)
    158                     raise InvalidId("%s is not a valid ObjectId" % oid)
    159             else:
--> 160                 raise InvalidId("%s is not a valid ObjectId" % oid)
    161         else:
    162             raise TypeError("id must be an instance of (str, ObjectId), "

InvalidId: 1 is not a valid ObjectId

In [22]: Post.objects.filter(author__id=1)

Any ideas?


Solution

  • I believe the "mongo way" would be to embed the author details in the post, as well as all comments, in Embedded Documents. Having multiple related collections (tables) isn't the best way to solve this problem in your case.

    Reduce your foreignKey usage as much as possible, and just embed the data. I believe MongoEngine has a Document and EmbeddedDocument class you can inherit from.

    Why do you want to use mongodb vs. mysql? You must have a HUGE blog... ;-)