我在stackoverflow上发现了一些类似的问题,但是没有任何问题可以解决我所需要的,所以任何帮助都将不胜感激。
我的模型:
class BlogPost(EmbeddedDocument):
title = StringField(required=True)
blog_url = StringField(required=True, unique=True)
content = StringField()
turned_into_bitly_link = BooleanField(default=False)
class Person(Document):
name = StringField
blog_posts = ListField(EmbeddedDocumentField(BlogPost), default=list)
对于每个blogpost.blog_url,我查询bitly api以查看url是否已被缩短。我需要做的是将从bitly获得的数据与数据库中相应的blogpost相匹配。从bitly返回的对象包含一个url字段,我需要使用该字段来匹配和更新数据库中相应的blogpost。还应该说我一次发一批博客网址到bitly,一个接一个是不行的。
给定一组blog-posts和bitly对象,所有这些都源于给定的个人:
person=person.objects.get(名称精确为'bobsmith')
如何通过“唯一URL”字段选择嵌入到我的Person对象中的特定博客文章?
作为一个权宜之计,我想我可以在person对象中遍历blog_posts,如果blog_post.url与bitly对象中的url匹配,那么我可以将转换后的_更新为bitly_link字段,但我不确定这是最有效的方法。
希望这有意义。我很高兴澄清,并提前感谢任何建议。
本
最佳答案
可以使用位置运算符更新匹配的嵌入文档。
下面是测试的一个例子(https://github.com/mongoengine/mongoengine/blob/master/tests/test_queryset.py l313)
def test_update_using_positional_operator(self):
"""Ensure that the list fields can be updated using the positional
operator."""
class Comment(EmbeddedDocument):
by = StringField()
votes = IntField()
class BlogPost(Document):
title = StringField()
comments = ListField(EmbeddedDocumentField(Comment))
BlogPost.drop_collection()
c1 = Comment(by="joe", votes=3)
c2 = Comment(by="jane", votes=7)
BlogPost(title="ABC", comments=[c1, c2]).save()
BlogPost.objects(comments__by="jane").update(inc__comments__S__votes=1)
post = BlogPost.objects.first()
self.assertEquals(post.comments[1].by, 'jane')
self.assertEquals(post.comments[1].votes, 8)