CodingGo Technology Community

Free programming learning platform

Author: Xiao Jiang, python enthusiast, self-study, try crawler, Django development and big data, not CS major background. I mainly use MATLAB in school, but occasionally use Python in my work. Blog homepage: www.cae-space.cn/

Use MongoDB as a back-end database in Django projects without changing Django’s ORM framework. Djangos user manager adds and modifies files in the MongoDB database.

usage

1.pip install djongo

2. Add the following code to setting.py in your Django project:

  

DATABASES = {

       'default': {

           'ENGINE': 'djongo',

           'NAME': 'your-db-name',

       }

   }
Copy the code

Run Manage.py Makemigrations and Manage.py Migrate (only needed when first tables are created in MongoDB)

4. Complete.

Requirements:

1.Python3.6 or later

2.MongoDB 3.4 or later

3. If a nested query or subquery is used in the project database, for example:

  

inner_qs = Blog.objects.filter(name__contains='Ch').values('name')

entries = Entry.objects.filter(blog__name__in=inner_qs)
Copy the code

MongoDB3.6 and above is required.

How does it work?

Djongo’s changes to the Django ORM framework are minimal, which means there are no unnecessary errors. It turns SQL string queries into MongoDB file queries. At this point, all django-related functions, databases, and so on work this way.

Djangos service modules:

  

'django.contrib.admin',

'django.contrib.auth',    

'django.contrib.sessions',
Copy the code

And all the others.

Django in usage

The Djongo connector for MongoDB ensures that you can: — reuse Django database /ORM framework — work with raw Django variables — validate your code beforehand — minor SQL JOIN operations

See Integrating Django with MongoDB for more details. If your project uses a complex database, you can also get expert support.

Add data files using the Django user administration module

Say you want to use Django to create a blog platform that uses MongoDB as a back-end database. Define the Blog table in your Blog project app/models.py:

fromdjongo import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: Abstract = True then embed the Blog into the Entry via EmbeddedModelField: class Entry(models.model): Blog = models. EmbeddedModelField (model_container = blog,) headline = models. CharField (max_length = 255) in the admin. Py registration Entry:  fromdjango.contrib import admin from .models import Entry admin.site.register(Entry)Copy the code

Complete the setup, then go to localhost:80000/admin/ and you will see the following results.

Query embedded data fields

In the example above, we want to query all names beginning with Beatles using the following query method:

  

entries = Entry.objects.filter(blog__startswith={'name': 'Beatles'})
Copy the code

See using MongoDB data fields in Django for more information.

Djongo manager

The Djongo manager extends the functionality of the Django manager. It lets you use all of PyMongo’s API commands. A custom manager like the Djongo manager can be defined in the model.

  

class Entry(models.Model):

blog = models.EmbeddedModelField(

model_container=Blog,

    )

headline = models.CharField(max_length=255)

objects = models.DjongoManager()
Copy the code

The use of the manager is the same as the Djongo manager: POST = entry.objects.get (PK =pkey) will get an object with the primary key Pkey.

Operate directly on Pymongo

MongoDB has very powerful query commands and DjongoManager allows you to fully use them.

  

classEntryView(DetailView):

defget_object(self, queryset=None):

index = [i for i in Entry.objects.mongo_aggregate([

            {

                '$match': {

                    'headline': self.kwargs['path']

                }

            },

        ])]

return index
Copy the code

You can use any PyMongo command directly by prefixing the command name with mongo. For example, use Aggregate for Blogpage, which is stored as a table in SQL and as a collection in MongoDB, changing the function name to MongoAggregate. Insert a file directly into the model (instead of using.save()), use Mongoinsertone ().


Click below to read the original text to join the course

Netease Cloud Class “Python Web Development Actual Combat”