pythondjangomongodbdjango-nonrel

Retrieve the subset of fields by querying the embedded field


Is it possible to retrieve the subset of fields using Django mongodb nonrel. I am totally new to python, but have good knowledge in mongo.

My requirement is very straight forward, I wanted to query the collection by its embedded field and return only some specific fields

I could do that in mongodb by

db.Contract.find({'owner.name':'Ram'},{'address':1})

and I tried this in django

Contract.objects.filter(owner__name='Ram')

but it throws an error

raise FieldError("Join on field %r not permitted. Did you misspell %r for the lookup type?" % (name, names[pos + 1])) FieldError: Join on field 'owner' not permitted. Did you misspell 'name' for the lookup type?

am totally struck here. I believe i have my models as specified in the documentation.

class SimplePerson(models.Model):
    name = models.CharField(max_length=255)
    user_key = models.CharField(max_length=255)


class Contract(models.Model):
    owner = EmbeddedModelField('SimplePerson')
    title = models.CharField(max_length=120, )

This is really weird. I could't find any reference in the documentation site about how to query the embedded field & retrieve the subset of fields.

Finally I used raw_query to query the embedded field

Contract.objects.raw_query({'owner.name':'Ram'})

But still not able to figure out how to retrieve the subset of fields. Can someone help me out?


Solution

  • Subobject filters aren't possible yet so you need to drop down to raw_query (which you already figured out). To retrive a subset of fields, use .values('field1', 'field2', ...).