NotUniqueError using django and mongoengine

583 Views Asked by At

I am using django and mongoengine. This is the error I am getting time and again when I try to save a newly created instance using .save() method.I was able to create a model instance first time but after that any post request is raising this error. Here's my Document structure:

class Client(DynamicDocument):
   name = fields.StringField(required=True,max_length=30) 
   uuid = fields.UUIDField(default=uuid.uuid4())
   contactEmail = fields.EmailField(required=True,max_length=30)
   contactPhone = fields.StringField(required=True,max_length=30)
   contactPerson = fields.StringField(required=True,max_length=30)

class ClientSerializer(mongoserializers.DocumentSerializer):

    class Meta:
        model = Client
        fields = ('id','name','uuid','contactEmail','contactPhone','contactPerson')

and here's where am making post request:

def post(self, request, format=None):
    serializer = ClientSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

but i catch the error:

NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection: project.client index: UUID_1 dup key: { : null })

I am stuck here.Please tell me where I went wrong since I am a noob to django.Any help would be highly appreciated.

2

There are 2 best solutions below

6
AudioBubble On

yo need set default as function: try remove the parentheses:

uuid = fields.UUIDField(default=uuid.uuid4())
#                                         ^^^

to

uuid = fields.UUIDField(default=uuid.uuid4)
#                                        ^^^

and try in serializer, declaring uuid field explicitly:

class ClientSerializer(mongoserializers.DocumentSerializer):
    uuid = serializers.UUIDField()
0
nesdis On

Django is a web framework that basically relies on a relational backend (eg sql) to save all its models. On the other hand MongoEngine is a ORM wrapper around MongoDB. Django has its own ORM type wrapper in the form of models.

To use Django with MongoEngine, either try Django-nonrel or try djongo which connects a relational Django to MongoDB.

Using Django Models with MongoEngine will not work always. Alternatively It's better to use MongoEngine ORM to save your models.