I would dearly love some feedback on the model below. Its a basic commenting structure where Users can comment on a variety of objects in the model. I have denormalised to make querying simpler, but I'm not sure if I've over/under done it. The model tests fine, but it all feels a little clunky. Any feedback would be awesome, thanks.
#####################################################################
# Base ##############################################################
class Base():
def __init__(self, **kwargs):
self._ClassName = self.__class__.__name__
self._Created = datetime.now()
self.__dict__.update(kwargs)
def __repr__(self):
return '<%s>' % self.__class__.__name__
#####################################################################
# Comment ###########################################################
class Comment(Base):
def __init__(self, username, person, comment, parent, **kwargs):
self.Username = username
self.Person = person
self.Comment = comment
self.Parent = parent
self.__dict__.update(kwargs)
def _save(self):
#save to Comments
db.Comments.save(self.__dict__)
#save to parent collection
parent_obj = db.dereference(self.Parent)
query = {'_id':parent_obj['_id']}
update = {'$addToSet':{'Comments':self.__dict__}}
db[parent_obj['_Collection']].find_and_modify(query, update, safe=True)
#save to people collection
query = {'_id':self.Person.id}
db.People.find_and_modify(query, update, safe=True)
def _remove(self):
#remove from Comments
query = {'_id':self._id}
db.Comments.remove(query, safe=True)
#remove from parent collection
query = {'Comments._id':self._id}
update = {'$pull':{'Comments':self.__dict__}}
db[self.Parent.collection].find_and_modify(query, update, safe=True)
#remove from people collection
db.People.find_and_modify(query, update, safe=True)
def __str__(self):
return '%s - %s...' % (self.Username, self.Comment[:10])
person = {'Username':'foobarman'}
db.People.save(person, safe=True)
program = {'Title':'the foobar', '_Collection', 'Programs'}
db.Programs.save(program, safe=True)
comment = Comment(
person['Username'],
DBRef('People', person['_id']),
'this is a comment about the foobar program',
DBRef(program['_Collection'], program['_id']))
comment._save()
# find latest 10 comments
list(db.Comments.find().sort('_Created', -1).limit(10))
# find all comments for username
db.People.find_one({'Username':'foobarman'})['Comments']
# find all comments for program
db.Programs.find({'Title':'the foobar'})['Comments']
# find all comments for program by user
list(db.Comments.find({
'Parent':DBRef(program['_Collection'], program['_id']),
'Username':'foobarman'}))