Nilesh
Nilesh

Reputation: 79

Django with Mongodb not creating id

I am trying Mongodb with Django and for that I am using djongo engine. I have created a simple model with two fields

class questions(models.Model):
    question = models.CharField(max_length=3000)
    answer = models.CharField(max_length=300000)

I ran the makemigrations and migrate. Using the admin option I am trying to add the data but when I am adding the record its creating with id as none. Please refer the below screenshots. enter image description here enter image description here From similar questions from the internet I tried to add the site Id in settings.py. Delete the migration files and rerun the migration but no luck. When I checked the 0001_initial.py I found the model as below which has Id field.


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='questions',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('question', models.CharField(max_length=3000)),
                ('answer', models.CharField(max_length=300000)),
            ],
        ),
    ]

I browse the data with Mongodb compass, there is no autogenerated ID field. Now I am stuck and not able to figure out what exactly going wrong. Please help.. Thank you.

Upvotes: 2

Views: 1598

Answers (1)

kholodnyi
kholodnyi

Reputation: 21

For proper Django admin integration you can add the _id field to your model:

from djongo import models


class questions(models.Model):
    _id = models.ObjectIdField()
    # other fields ... 

Since djongo.models contains all the standard django.db.models classes you can just replace:

from django.db import models

with

from djongo import models

Upvotes: 2

Related Questions