Cannot query using IDs - Django MongoDB Engine

1.8k views Asked by At

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?

3

There are 3 answers

1
Marcus Blankenship On BEST ANSWER

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

0
moskrc On

May be:

author = Author.objects.get(pk=1)
posts = author.post_set.all()
0
deleted77 On

It's impossible to mix those two engines. The simplest explanation for this is that MongoDB primary keys are string-like objects and *SQL pks are integers. You can't use both, chose one.