1. Introduction
It used to be developed using the django+ relational database MySQL, which now requires the use of django+ non-relational database MongoDB, which can be used directly in Django for MySQL operations, but Django does not support MongoDB, This way we need to use the Mongoengine module to implement the Django model encapsulation
2. Pre-Preparation
- Install the necessary modules Mongoengine and Pymongo (because Mongoengine relies on Pymongo, all install Mongoengine First, will automatically install Pymongo)
# because using direct PIP installation is slow, it is recommended to use the Watercress image pip install mongoengine-i https://pypi.douban.com/simple
3. Basic Connection operation
From mongoengine Import * # database name, IP address, port, account number, password, account configuration database, authentication methodConnect (' project ', host= ' localhost ', port=27017, username= ' root ', password= ' 123456 ', authentication_source= ' Admin ', authentication_mechanism= ' scram-sha-1 ') # If MongoDB is local and does not require authentication, just fill in the database nameConnect (' project ') class Post (Document):title = Stringfield (max_length=120, required=true)# Similar to foreign keysauthor = Referencefield (User, Reverse_delete_rule=cascade)tags = ListField (Stringfield (max_length=30))# Inheritance Settingsmeta = {' Allow_inheritance ': True} # Inheritanceclass Textpost (Post):
content = Stringfield ()
class Imagepost (Post):
image_path = Stringfield ()
class Linkpost (Post):
Link_url = Stringfield ()# Add Data
< Span class= "o" >< Span class= "o" >< Span class= "o" >ross = User (email= ' [email protected] ', First_name= ' Ross ', Last_name= ' Lawley '). Save ()
# < Span class= "o" >< Span class= "o" >< Span class= "o" > You can also add thisross = User (email= ' [email protected] ')ross.first_name = ' Ross 'ross.last_name = ' Lawley 'Ross.save ()# Get Data
For post in post.objects:
print (post.title)
# Get Specific data contentFor post in post.objects (tags= ' MongoDB '):print (post.title) # Get the number of specific data contentnum_posts = post.objects (tags= ' MongoDB '). Count ()print (' Found {} posts with tag ' MongoDB '. Format (num_posts))4. Supported Field Types-Binaryfield-Booleanfield-Complexdatetimefield-Datetimefield-Decimalfield-Dictfield-DynamicField-Emailfield-Embeddeddocumentfield-Embeddeddocumentlistfield-Filefield-Floatfield-Genericembeddeddocumentfield-Genericreferencefield-Geopointfield-ImageField-Intfield-ListField-Mapfield-Objectidfield-Referencefield-Sequencefield-Sortedlistfield-Stringfield-Urlfield-Uuidfield-Pointfield-Linestringfield-Polygonfield-Multipointfield-Multilinestringfield-Multipolygonfield
Django combined with Mongoengine for MongoDB operation