2011-09-02 10 views
7

Sto cercando di definire i metodi per eseguire controlli e aggiornamenti in un elenco di documenti incorporati in mongoengine. Qual è il modo corretto di fare ciò che sto cercando di fare. Il codice è sottoQual è il modo corretto di aggiornare un elenco di documenti incorporati in mongoengine?

class Comment(EmbeddedDocument): 
    created = DateTimeField() 
    text = StringField() 

class Post(Document): 
    comments = ListField(EmbeddedDocumentField(Comment)) 

    def check_comment(self, comment): 
     for existing_comment in self.comments: 
      if comment.created == existing_comment.created and 
       comment.text == existing_comment.text: 
       return True 
     return False 

    def add_or_replace_comment(self, comment): 
     for existing_comment in self.comments: 
      if comment.created == existing_comment.created: 
       # how do I replace? 

     # how do I add? 

È questo anche il modo corretto di andare su qualcosa di simile?

risposta

1

È necessario trovare l'indice del commento esistente.

È quindi possibile sovrascrivere il vecchio commento con il nuovo commento (dove i è l'indice), ad esempio:

post.comments[i] = new_comment 

poi basta fare un post.save() e mongoengine convertirà che a un'operazione $set.

In alternativa, si può solo scrivere il $set esempio:

Post.objects(pk=post.pk).update(set__comments__i=comment) 
2

È possibile usare un EmbeddedDocumentListField al posto di un elenco di documenti incorporati. In questo modo si ottiene l'accesso ad alcuni handy methods come filtro, creare o aggiornamento:

class Comment(EmbeddedDocument): 
    created = DateTimeField() 
    text = StringField() 

class Post(Document): 
    comments = EmbeddedDocumentListField(Comment) 

    ... 

    def add_or_replace_comment(self, comment): 
     existing = self.comments.filter(created=comment.created) 
     if existing.count() == 0: 
      self.comments.create(comment) 
     else: 
      existing.update(comment) 

(codice non testato)

+1

aggiornamento nota prende argomenti chiave in modo commento deve essere un dizionario di valore chiave coppie che si scompattano 'existing.update (** comment)' –

Problemi correlati