Yash
Yash

Reputation: 283

pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection:

I am trying to use MongoDB with Django Framework using the library Djongo. I am stuck in a particular problem right now where I can't store more than 1 document in MongoDB. After first data insert, Django Throws pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection:

Even though I only have one document. Also I am not setting '_id' field in my models. So its Djongo who does it for me.

My Model.py

from djongo import models


# Create your models here.
class Data(models.Model):
    company_name = models.CharField(max_length=200)
    company_url = models.CharField(max_length=200)
    company_logo = models.CharField(max_length=200)
    objects = models.DjongoManager()

Upvotes: 0

Views: 1993

Answers (1)

Falcon Goldman
Falcon Goldman

Reputation: 26

Add "_id" value in you Data Class.

As you havent't added that, Djongo is automatically creating a null value for that. So it works for the first time. When you are trying to insert second document, it again creates a document with "_id" value of null and thus throws the duplicate Key Error. Add this line in your Data Class

_id = models.ObjectIdField(auto_created=True, unique=True, primary_key=True)

Note: - Make sure to use the name "_id" and not "id" as in MongoDB, its "_id" and not "id"

Upvotes: 1

Related Questions