DEV Community

Ankithajitwta
Ankithajitwta

Posted on

Database in Django

Hi, I'm Ankitha working as junior software engineer at Luxoft. Here is an article on Django Database, which I've started using recently.

Introduction:

MongoDB is a popular NoSQL database that stores data in JSON-like documents with dynamic schema. It offers scalability, performance, and flexibility that make it a popular choice for modern applications. In this article, we will explore how to use MongoDB with Django, a popular Python web framework.

Setting up MongoDB with Django

Before we dive into the code, we need to set up MongoDB with Django. We will use the djongo library to connect Django with MongoDB. Here are the steps to set up MongoDB with Django:

In the settings.py file of your Django project, add the following configurations:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'mydatabase',
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating a MongoDB Model in Django

Now that we have set up MongoDB with Django, we can create a model that uses MongoDB as its database backend. Here is an example model that stores information about books:

from djongo import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.title
Enter fullscreen mode Exit fullscreen mode

In this example, we use the djongo library to define our model. The title, author, and description fields are defined using Django's CharField and TextField models.

To specify that this model should use MongoDB as its database backend, we simply import models from djongo instead of django.db.models. The Book model will automatically create a collection in MongoDB with the name book.

Querying MongoDB with Django

Now that we have created our MongoDB model, we can query the database using Django's built-in QuerySet API. Here are some examples of how to query our Book model:

books = Book.objects.all()


books = Book.objects.filter(author='John Doe')

books = Book.objects.order_by('title')


book = Book.objects.first()


book = Book.objects.last()
Enter fullscreen mode Exit fullscreen mode

In this example, we use the same QuerySet API that we would use with a traditional relational database. The all() method returns all books, the filter() method filters books by author, and the order_by() method orders books by title.

MongoDB is a popular NoSQL database management system that is designed to handle large amounts of unstructured data. Its objectives are centered around providing a scalable, high-performance, and flexible platform for storing and querying data. Here are some of the key objectives of MongoDB:

Scalability:

MongoDB is designed to scale horizontally, meaning it can handle large volumes of data by adding more servers to the database cluster. It allows users to easily shard data across multiple servers to improve performance and distribute the workload.

Performance:

MongoDB is optimized for high-speed data access and processing. It uses memory-mapped files to improve read and write performance, and its indexing capabilities allow for fast querying of large datasets.

Flexibility:

MongoDB is a schema-less database, which means that it does not require a predefined data model or structure. This makes it ideal for storing unstructured and semi-structured data, such as JSON documents, which can be easily modified and updated.

Availability:

MongoDB is designed to provide high availability and fault tolerance. It uses a distributed architecture that ensures that data is replicated across multiple servers, so even if one server fails, the system can continue to operate without any downtime.

Ease of use:

MongoDB is easy to use and administer, with a simple and intuitive API for accessing and manipulating data. It also provides a rich set of tools and utilities for managing the database, including a web-based admin interface, command-line tools, and drivers for popular programming languages like Python, Java, and Ruby.

import pymongo


client = pymongo.MongoClient('mongodb://localhost:27017/')


db = client['mydatabase']


mycollection = db['mycollection']



data = {
    'name': 'John Doe',
    'age': 30,
    'address': {
        'street': '123 Main St',
        'city': 'Anytown',
        'state': 'CA'
    }
}
Enter fullscreen mode Exit fullscreen mode

mycollection.insert_one(data)

In this example, we first connect to the MongoDB server using the pymongo driver. We then select the database we want to use and create a collection named mycollection.

Next, we define the data we want to store in the database as a Python dictionary. In this case, we have a simple document with a name, age, and address field.

Finally, we insert the data into the mycollection collection using the insert_one() method. This will create a new document in the collection with the data we defined.

Note that pymongo is just one of many drivers available for working with MongoDB. Other popular drivers include the official MongoDB driver for Python, as well as drivers for other programming languages like Java, Node.js, and Ruby.

Conclusion:

In this article, we explored how to use MongoDB with Django using the djongo library. We created a model that stores information about books and demonstrated how to query the database using Django's built-in QuerySet API. MongoDB offers scalability, performance, and flexibility that make it a popular choice for modern applications, and integrating it with Django is a straightforward process using djongo.

Top comments (1)

Collapse
 
sloan profile image
Sloan the DEV Moderator

Hey, this article seems like it may have been generated with the assistance of ChatGPT.

We allow our community members to use AI assistance when writing articles as long as they abide by our guidelines. Could you review the guidelines and edit your post to add a disclaimer?