0

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
Sebastian Karlsson
  • 715
  • 1
  • 8
  • 19
  • did you check with a debugger for the ID of the category and the result of `CategoryFacade.categoryExists(category)` during the second call? – ezdazuzena Jan 16 '18 at 12:42
  • @ezdazuzena This is the code for that: ` @staticmethod def categoryExists(name): try: return Category.objects.get(name=name) is not None except DoesNotExist: return False ` – Sebastian Karlsson Jan 16 '18 at 12:44
  • @SebastianKarlsson did you ever manage to solve this? I'm running into the same issue – Corleone Jul 23 '20 at 23:56

0 Answers0