RadiantHex
RadiantHex

Reputation: 25567

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?

Upvotes: 0

Views: 1864

Answers (3)

deleted77
deleted77

Reputation: 147

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.

Upvotes: -1

moskrc
moskrc

Reputation: 1228

May be:

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

Upvotes: 0

Marcus Blankenship
Marcus Blankenship

Reputation: 521

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

Upvotes: 2

Related Questions