Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Django projects connect to MongoDB

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to connect the Django project to MongoDB. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Django and MongoDB settin

For the integration to work, you should have a Django and MongoDB setting. If you have Python on your machine, you can use pip to install Django. If you want to install Django in a specific environment rather than the entire system, you can create a virtual environment. Use pip/pip3 depending on your version of Python:

Installation:

Windows:

Pip install virtualenvwrapper-win

Mac OS / Linux:

Pip install virtualenvwrapper creation:

Windows:

Mkvirtualenv MyProjectEnvt

Mac OS / Linux:

Virtualenv MyProjectEnvt activation:

Mac OS / Linux

Source MyProjectEnvt/bin/activate

Windows:

Workon MyProjectEnvt

To deactivate the virtual environment, you simply type the command deactivate. Now install Django using pip install Django. To start the Django project, go to the folder where you want to start the project and use the following command:

Django-admin startproject.

For example:

C:\ Users\ myuser\ project_files > django-admin startproject MyFirstDjangoProj

C:\ Users\ myuser\ project_files > cd MyFirstDjangoProj

To create an application, use the following command:

Python manage.py startapp myfirstapp

If you are using the Python version > = 3.0, replace the python in the command with python3. Within the application, we can have many models that will map to collections and documents in MongoDB. After you start the project, all files will be available in the project folder. Start the server using the python manage.py runserver command. Your Django setup is now complete. If you haven't already set up MongoDB, use MongoDB Atlas to take full advantage of cloud hosting. Atlas works seamlessly with all major cloud providers.

Use PyMongo to connect Django and MongoDB

PyMongo is very efficient for writing JSON data to MongoDB and allows MongoDB queries to be used in the Python code itself. We can use PyMongo to retrieve the data in the dictionary like syntax. Use the pip/pip3 command to easily install PyMongo:

Pip install pymongo [snappy,gssapi,srv,tls]

If you are using a virtual environment, you must install pymongo in the..\ venv\ Lib\ site-packages folder. In addition, install dnspython to use mongodb+srv:// URI and commands:

Pip install dnspython

With PyMongo, we can run multiple databases at the same time by specifying the correct database name for the connection instance.

Let's create a sample pymongo session. There are two ways to do this:

1. We can create a client in the utils file that can be used by any view that wants to interact with MongoDB. Create a utils.py file in your project folder (in the same location as manage.py) and instantiate the client:

From pymongo import MongoClientdef get_db_handle (db_name, host, port, username, password): client = MongoClient (host=host, port=int (port), username=username, password=password) db_handle = client ['db_name'] return db_handle, client

You can then use this method in. / myfirstapp/view.py.

two。 Another way to get a connection is to use connection_string:

From pymongo import MongoClientclient = pymongo.MongoClient ('connection_string') db = client [' db_name']

In

Connection_string = mongodb+srv://:@/?retryWrites=true&w=majority

For example:

Makemyrx_db = client ['sample_medicines'] # collection objectmedicines_collection = makemyrx_db [' medicinedetails']

You may have seen the Connection class in other code examples or tutorials. The connection has been deprecated, so do not use it.

If you are using the default port and host, just call MongoClient (). To connect to the localhost, we can explicitly specify the host and port as:

MongoClient ('localhost', 27017)

Or

Use the URL format MongoClient ('mongodb://localhost: 27017 Universe')

Since we have created the client here, we need to comment the DATABASES section in the settings.py file. Use triple quotes to annotate the same content.

Use MongoEngine to connect Django and MongoDB

MongoEngine is the ORM layer on top of PyMongo. Therefore, your system still needs PyMongo (> = 3. 4) to use MongoEngine.

Using MongoEngine to connect Django and MongoDB, you can use fields such as ListField and DictField to handle large amounts of unstructured JSON data.

First, install MongoEngine using the following command:

Pip install mongoengine

As we saw in the previous section, when using PyMongo, we must annotate the DATABASES section in settings.py. Then, to use MongoEngine, add the following:

Import mongoenginemongoengine.connect (db=db_name, host=hostname, username=username, password=pwd)

With MongoEngine, we must define a schema in the models.py file of the Django application. MongoDB is modeless. The architecture is executed only at the application level, making any future changes fast and easy. MongoEngine is similar to the default ORM for Django, but has the following changes in model.py:

Django's ORMMongoEnginefrom django.db import models

From mongoengine import Document, fields or from mongoengine import *

ModelDocumentmodels.CharFieldfields.StringField ()

The difference is that we are using a model, and when using MongoEngine, the model is replaced by documents and fields. There are many other tools that can be used with PyMongo.

Use Djongo to connect Django and MongoDB

Djongo is an improvement on PyMongo because developers do not have to write lengthy queries. It maps Python objects to MongoDB documents, that is, object document mapping (ODM). Djongo ensures that only clean data can enter the database. By using Djongo to perform integrity checks, application verification, and so on, there is no need to modify the existing Django ORM.

Install Djongo:

Pip install djongo

Now, go to your project folder (for example, MyFirstDjangoProj) and open the settings.py file. You can edit it on Textpad, Python IDE, or any editor. Search for DATABASES and change the setting to point to MongoDB. ENGINE will be djongo, and database name (NAME) will be your MongoDB database name.

DATABASES = {'default': {' ENGINE': 'djongo',' NAME': 'db-name',}}

If your database is not on the local host or is protected, you should also fill in CLIENT information, such as HOST, USERNAME, PASSWORD, and so on.

DATABASES = {'default': {' ENGINE': 'djongo',' NAME': 'your-db-name',' ENFORCE_SCHEMA': False, 'CLIENT': {' host': 'mongodb+srv://:@/?retryWrites=true&w=majority'}

Ensure that the application name is added to the INSTALLED_APPS settings of settings.py:

INSTALLED_APPS = ['myfirstapp',' django.contrib.admin', 'django.contrib.auth',' django.contrib.contenttypes', 'django.contrib.sessions',' django.contrib.messages', 'django.contrib.staticfiles',]

Now that we have the Django project (and application), you can create a collection in MongoDB using the following command:

Python manage.py makemigrations python manage.py migrate

Collections will be created (the Django model in the application-- note that we are talking about the application, not the project). You can check the same content by opening Django Admin. You can use the administrative GUI or manually insert data into the collection. To use the administrative console, open a browser and go to http://127.0.0.1:8000/admin (or localhost). You should create a superuser to enter the administrative console. If you don't have any models in your application, follow the Django tutorial on how to create and register models. If you want Djongo to be migration-free, set ENFORCE_SCHEMA: False in your database configuration. With this setting, the collection is created dynamically and Djongo does not convert SQL statements into MongoDB commands.

Django and MongoDB tutorials

Feel free to write the code or download the complete code from this GitHub repository. In this quick tutorial, we will demonstrate how to use PyMongo for simple CRUD operations. To do this, let's create a PyMongo session:

Import pymongo#connect_string = 'mongodb+srv://:@/?retryWrites=true&w=majority' from django.conf import settingsmy_client = pymongo.MongoClient (connect_string) # First define the database namedbname = my_client [' sample_medicines'] # Now get/create collection name (remember that you will see the database in your mongodb cluster only after you create a collectioncollection_name = dbname ["medicinedetails"] # let's create two documentsmedicine_1 = {"medicine_id": "RR000123456", "common_name": "Paracetamol" "scientific_name": "available": "Y", "category": "fever"} medicine_2 = {"medicine_id": "RR000342522", "common_name": "Metformin", "scientific_name": "", "available": "Y", "category": "type 2 diabetes"} # Insert the documentscollection_name.insert_many ([medicine_1 " Medicine_2]) # Check the countcount = collection_name.count () print (count) # Read the documentsmed_details = collection_name.find ({}) # Print on the terminalfor rin med_details: print (r ["common_name"]) # Update one documentupdate_data = collection_name.update_one ({'medicine_id':'RR000123456'} {'$set': {'common_name':'Paracetamol 500'}}) # Delete one documentdelete_data = collection_name.delete_one ({'medicine_id':'RR000123456'})

Next, you can connect to your MongoDB Atlas cluster and verify it.

This is the end of the article on "how to connect the Django project to MongoDB". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report