djongo Company with ID “None” doesn’t exist. Perhaps it was deleted?

Question:

I couldn’t find a solution among similar questions.

enter image description here

Using mongosh, the Company objects do exist, but in the admin, they show as object(None) and therefore cannot be edited due to error "Company with ID “None” doesn’t exist. Perhaps it was deleted?". I guess it is about the "id" detection, but can not fix it myself. Question: how to fix the code to make the Company object to be shown correctly, not as None.

myproject> db.companies_company.find()
[
  { _id: ObjectId("6145dd9a8bc9a685b2ae2375"), name: 'company1' },
  { _id: ObjectId("6145ddaa8bc9a685b2ae2377"), name: 'company2' }
]

models.py:

from django.db import models

# Create your models here.
class Company(models.Model):
    name = models.CharField(max_length=100, blank=False, null=False, unique=True)

admin.py:

from django.contrib import admin

# Register your models here.
from .models import Company

@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
    pass
Asked By: vadtam

||

Answers:

The manual setting of the _id field solved the issue.

from djongo import models

# Create your models here.
class Company(models.Model):
    _id = models.ObjectIdField()
    name = models.CharField(max_length=100, blank=False, null=False, unique=True)
Answered By: vadtam

This is how I had solved it. Add a UUIDField to your model and set it as primary key.

import uuid


id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100, blank=False, null=False)

Note: If you already have some objects in the admin panel of this model, then opening that object will still show the same error. It will come to effect only after you make these changes, perform the migrations and add a new object.Then while opening the newly added object you can’t see the error.

Answered By: Ajdal