Search code examples
pythonsqldjangodjango-modelsdjongo

Why do I get a userId duplicate key error even though my model does not have user as the primary key?


I have an Interactions model which inherits from the predefine django user model, but I have the messageId to be the primary key.

models.py:

class Interaction(models.Model):
messageId = models.TextField(max_length=5000,primary_key=True, unique = True)
user = models.OneToOneField(User, primary_key = False, on_delete=models.CASCADE)
reciever = models.TextField(max_length=5000,blank=True,default='')
sender = models.TextField(max_length=5000,blank=True,default='')
date = models.TextField(max_length=5000,blank=True,default='')
subject = models.TextField(max_length=5000,blank=True,default='')
label = models.TextField(max_length=5000,blank=True,default='')

I have a dictionary called data which stores the information required. In views.py

entry, created = Interaction.objects.get_or_create(messageId=data['id'])
entry.user = request.user
entry.sender = data['from']
entry.reciever = data['to']
entry.date = data['date']
entry.subject = data['subject']
entry.label = data['label']
entry.save()

So while running the code there are messages with the same user but obviously different message ids

user is not my primary key yet I keep getting the error djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "mainapp_interaction" SET "user_id" = %(0)s, "reciever" = %(1)s, "sender" = %(2)s, "date" = %(3)s, "subject" = %(4)s, "label" = %(5)s WHERE "mainapp_interaction"."messageId" = %(6)s Pymongo error: {'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: 5d02255b9ccf640b8c608ee1_mysitev6.mainapp_interaction index: user_id_1 dup key: { : 16 }'}


Solution

  • Doesn't matter that it's not the primary key. It's a OneToOneField, so there can be at most one entry per user in the database. Logically, I believe it should be a ForeignKey, and you don't need the primary_key=False flag.

    Also, I recommend using models.DateTimeField() for storing dates (I don't know the exact use of your model, but if the fields are what they say they are, you should consider this).

    Good luck!