Mongo as primary database in django

I want to use mongodb as my primary database with django, but when I make DATABASE dict in settings.py file, create a model and run migrations it throws error.

I want to use my mongodb(connection string) and use mongo-db atlas.

DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.dummy’,
}
}

Connection String:
mongodb+srv://(username):(password)@(my cluster).itos0qp.mongodb.net/

models.py:
class Department(models.Model):
dptId = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
superior = models.CharField(max_length=100)
empQty = models.IntegerField()

def __str__(self):
    return self.name

When I try to makemigrations it throws this error:

ERROR:
File “C:\Users\Axix Technologies\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\dummy\base.py”, line 20, in complain
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

django.db.backends.dummy is an internal placeholder to denote that an empty string was supplied. It shouldn’t be used.

You’ll need an app that supports Mongo as Django doesn’t support it ootb.

I recommend reading the Mongo guide on Django: Django Integration With MongoDB Tutorial | MongoDB

1 Like

<opinion>
A bad idea - an “anti-pattern”.
</opinion>

But, if you insist on doing this, see Django with MongoDB - Djongo and GitHub - doableware/djongo: Django and MongoDB database connector

1 Like

Okay! sir thank you for your precious time and effort. Will look into it.

Okay! sir thankyou for your precious time and effort. I will look into it.

I have 1 more question please what if I don’t use any database and keep the dict empty like this:

DATABASES = {}

What will be the circumstances to it, and for database, I’ll create custom mongodb-scripts in order to store my data on mongodb-atlas.

Something like this:
def department(request):
print(f"{request.session.get(‘username’)}")

context = {
    'data_dict': PERSONNEL,
    'title': 'Personnel | Department',
    'active_menu': 'personnel_department',
    'active_menu_heading': 'Organization',
}

if request.method == "POST":
    name = request.POST.get('name')
    superior = request.POST.get('superior')
    empQty = request.POST.get('empQty')

    try:
        context['msg'] = department_script.createDepartment({
            'name': name,
            'superior': superior,
            'empQty': empQty,
        })

    except Exception as e:
        return JsonResponse({'error': f'Failed to upload Department data. Error: {str(e)}'})

context['departments'] = department_script.getDepartments()

return render(request, 'admin/personnel/pages/organization/department.html', context)

mongodb-script:
def createDepartment(args):
counter = get_latest_record()
if counter is not None:
dptId = counter + 1
print(f"Department ID: {dptId}")

    record = {
        'dptId': dptId,
        'name': args.get('name'),
        'superior': args.get('superior'),
        'empQty': args.get('empQty'),
    }

else:
    dptId = 1
    print(f"Department ID: {dptId}")

    record = {
        'dptId': dptId,
        'name': args.get('name'),
        'superior': args.get('superior'),
        'empQty': args.get('empQty'),
    }

try:
    insert_record = collection.insert_one(record)
    return f"Record with ID: {insert_record.inserted_id} inserted successfully!!!"

except DuplicateKeyError as e:
    return f"Duplicate Error: {e}"

except Exception as e:
    return f"Error: {e}"

How do rate this approach, would it be good and worth applying, If I have to use mongodb with django, but point to be noted I am not allowed to use any other database.

Thank you !!

Quoting directly from Settings | Django documentation | Django

The DATABASES setting must configure a default database;

[emphasis added]

First reaction. Bull. (Personally, I have no patience with organizations that supposedly put restrictions in like this.) Policies and procedures are subservient to business requirements. If you are required to use Django, then someone needs to understand that you have been given contradictory requirements.

Or, Don’t use Django. Use Flask or some other framework. Django is very closely tied to the relational model.

Or, use SQLite. Technically, it’s a file, not a database engine, and may be sufficient.

1 Like

Thank you for your advice.

Actually, I’ve told to design this product on django with postgresql, I completed it, but there were some limitations, because this product has 2 parts 1 will be hosted and the other one will be locally on the client’s pc, they want to use 1 database, which could link both these parts.

So, now tell me how can I handle this. If I use sqlite3, or any other sql database.

Or, any other hint or information, which could help me sync the data on cloud and locally. And also save the data on mongodb(as our own backup) .

Thank you !!

Now you’re getting into areas of system architecture and design that fall well-outside what can be reasonably discussed in a forum such as this.

It would be irresponsible of me to offer ideas and suggestions without a much more detailed understanding of the system being proposed and that’s not really an appropriate topic here.

I suggest you find a firm with expertise in hybrid / distributed systems and hire them for your design. It would be money well-spent.

1 Like

Okay! Thank you for your time Mr. KenWhitesell, have a nice day.