我有这些模型:
class Podcast(Document):
name = StringField(max_length=200, required=True)
category_id = ReferenceField(Category)
以及:
^{pr2}$当我尝试插入一个新的播客,它的类别与另一个播客已经有相同时,我得到以下错误:
mongoengine.errors.NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection:myapp.podcast index: category_id.name_1 dup key: { : null })
如何插入播客:
category = 'Comedy'
if not CategoryFacade.categoryExists(category):
cat = CategoryFacade.createCategory(category)
else:
cat = CategoryFacade.get(category)
podcast = {
'name': pod['name'] if 'name' in pod else None,
'category_id': cat.to_dbref()
}
PodcastFacade.createPodcast(podcast)
PodcastFacade中的createPodcast方法:
@staticmethod
def createPodcast(kwargs):
c = Podcast(**kwargs)
c.save()
return c
categoryExists方法:
@staticmethod
def categoryExists(name):
try:
return Category.objects.get(name=name) is not None
except DoesNotExist:
return False
目前没有回答
相关问题 更多 >
编程相关推荐