Testing existence of referenced documents?

13 views
Skip to first unread message

Chris Faulkner

unread,
Jul 2, 2012, 5:03:43 PM7/2/12
to mongoen...@googlegroups.com
Say you have the following class:

class Person(Document):
            name = StringField()
            supervisor = ReferenceField('self')


When looking up a document directly you can do something like:

person = Person.objects(name='bob').first()
if not person:
    # handle failed lookup


Is there a way to do something like this with referenced documents?  I need a way to test that the referenced document still exists.

Ideally, something like the following work work:

person = Person.objects(name='bob').first()
if not person.supervisor:
    # handle failed lookup


This works if person.supervisor is None, but if person.supervisor references a document that has since been deleted then you'll instead get back a DBRef object (since dereferencing failed), which will evaluate to true in above code.

The closest solution I've found is to check if the referenced document is an instance of DBRef, but it makes for ugly code.

Anyone have a better way of handling this?
Reply all
Reply to author
Forward
0 new messages