Skip to content

Instantly share code, notes, and snippets.

@borntyping
Created January 15, 2013 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borntyping/4539630 to your computer and use it in GitHub Desktop.
Save borntyping/4539630 to your computer and use it in GitHub Desktop.
The result of me trying to get mongoengine deletion rules to work, as the documentation is a little confusing (or even misleading).
from mongoengine import *
class QuerySetProperty(object):
"""A set of documents belonging to an entity from another collection
Basically, provides the functionality a backref would provide."""
def __init__(self, cls):
self.cls = cls
def __get__(self, instance, owner):
return self.cls.objects(entity=instance)
class Post(Document):
content = StringField()
entity = ReferenceField('Entity', dbref=False)
def __repr__(self):
return "<Post: '{}' owned by {}>".format(self.content, self.entity)
def __str__(self):
return self.content
class Entity(Document):
name = StringField()
posts = QuerySetProperty(Post)
def __repr__(self):
return "<Entity: {}>".format(self.name)
def __str__(self):
return self.name
Entity.register_delete_rule(Post, 'entity', CASCADE)
db = connect('examples')
Entity.drop_collection()
Post.drop_collection()
sam = Entity(name="Sam").save()
post = Post(entity=sam, content="Hello world").save()
print sam.posts, Post.objects
# [<Post: 'Hello world' owned by Sam>], [<Post: 'Hello world' owned by Sam>]
sam.delete(safe=True)
print Post.objects
# []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment