Django primary key error (Djongo driver)

3.4k views Asked by At

I'm writing a website on Python, Django using MongoDB and Djongo (to connect Mongo with Django) and I want to be able to add and delete documents from the database using my website. But I have an error while doing it.

If I don't set primary key in my models then I can successfully add documents, but when try to delete have AssertionError (object can't be deleted because its id attribute is set to None), however when I check the database _ID field is there created automatically. If I do set primary key by primary_key = True in models.py I can successfully delete a document, but on insertion I got AssertionError (No exception message supplied).

Also, if primary key is not set, then I cannot access documents from admin panel, but can add them to the database (through admin panel); and if pk is set then from admin panel I can access, delete and edit, but cannot add a new document to the database.

This is my model:

class DevList(models.Model):
    dev_num = models.CharField(max_length = 200 , primary_key = True)
    dev_name = models.CharField(max_length = 200)
    dev_descr = models.CharField(max_length = 200)
    dev_type = models.CharField(max_length = 200)

If no pk is set, then I delete primary_key = True line

My view is simple post form and I use d.save() to save and d.delete() to delete.

2

There are 2 answers

3
Astik Anand On

Actually, Django by default provides an id field with every model which is by default set as primary key.

Now, when you can set other field as primary key by primary_key=True. But for smoother operation I will advice you to use unique=True on other fields.

dev_num = models.CharField(max_length = 200 , unique = True)
0
Aqueuse On

I had a similar problem using MongoDB + Django with the Djongo driver (cannot delete objects in the admin page of my website because the _id is not an integer but an ObjectID() wich is not recognized as a valid integer).

This is how I solved it (the quickest way) : I set for my object an id with the models.PositiveIntegerField type and I use the primary_key argument with the True value) :

class MyObject(models.Model):
    id = models.PositiveIntegerField(primary_key=True)
    title = models.CharField(max_length=100)
    other_field = models.TextField(blank=True)

    def __str__(self):
        return f"{self.title}"

This way, the _id of mongoDB is not used but the admin system still find a valid integer for the primary key. That has been tested succesfully, problem solved.