So I have these models:
class Podcast(Document):
name = StringField(max_length=200, required=True)
category_id = ReferenceField(Category)
and:
class Category(Document):
name = StringField(max_length=120, required=True, unique=True)
When I try to insert a new podcast that has a category that another podcast already has, I get this error:
mongoengine.errors.NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection:myapp.podcast index: category_id.name_1 dup key: { : null })
How I am inserting a podcast:
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)
the createPodcast method in PodcastFacade:
@staticmethod
def createPodcast(kwargs):
c = Podcast(**kwargs)
c.save()
return c
The categoryExists method:
@staticmethod
def categoryExists(name):
try:
return Category.objects.get(name=name) is not None
except DoesNotExist:
return False