python,mongoengine ReferenceField重复键

2024-09-30 00:39:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这些模型:

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

Tags: tokeynameidreturnsavecatpodcast

热门问题