這篇文章帶給大家的內容是關於django開發之mongodb的配置與使用,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
今天整理了一下在django專案中如何使用mongodb, 環境如下:ubuntu18.04, django2.0.5, drf3.9, mongoengine0.16
第一步:在settings.py中設定mongodb和mysql,配置如下(可以同時使用mysql和mongodb):
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 数据库引擎 'NAME': 'django_test2', # 你要存储数据的库名,事先要创建之 'USER': 'root', # 数据库用户名 'PASSWORD': 'wyzane', # 密码 'HOST': 'localhost', # 主机 'PORT': '3306', # 数据库使用的端口 }, 'mongotest': { 'ENGINE': None, } } import mongoengine # 连接mongodb中数据库名称为mongotest5的数据库 conn = mongoengine.connect("mongotest")
第二步:向mongodb插入資料
1、插入json類型資料
models.py: import mongoengine class StudentModel(mongoengine.Document): name = mongoengine.StringField(max_length=32) age = mongoengine.IntField() password = mongoengine.StringField(max_length=32) views.py: from rest_framework.views import APIView class FirstMongoView(APIView): def post(self, request): name = request.data["name"] age = request.data["age"] password = request.data["password"] StudentModel.objects.create(name=name, age=age, password=password) return Response(dict(msg="OK", code=10000))
插入資料格式為:
{ "name": "nihao", "age": 18, "password": "123456" }
2、插入含有list的json資料
models.py: import mongoengine class Student2Model(mongoengine.Document): name = mongoengine.StringField(max_length=32) # 用于存储list类型的数据 score = mongoengine.ListField() views.py: from rest_framework.views import APIView class FirstMongo2View(APIView): def post(self, request): name = request.data["name"] score = request.data["score"] Student2Model.objects.create(name=name, score=score) return Response(dict(msg="OK", code=10000))
插入資料格式為:
{ "name": "test", "score": [12, 13] }
3、插入含有dict和list的複雜json資料
models.py: import mongoengine class Student3Model(mongoengine.Document): name = mongoengine.StringField(max_length=32) # DictField用于存储字典类型的数据 score = mongoengine.DictField() views.py: from rest_framework.views import APIView class FirstMongo3View(APIView): def post(self, request): name = request.data["name"] score = request.data["score"] Student3Model.objects.create(name=name, score=score) return Response(dict(msg="OK", code=10000))
插入資料格式為:
{ "name": "test", "score": {"xiaoming": 12, "xiaoli": 13} } 或者: { "name": "test", "score": {"xiaoming": 12, "xiaoli": {"xiaozhao": 14}} } 或者: { "name": "test", "score": {"xiaoming": 12, "xiaoli": {"xiaozhao": {"xiaoliu": 12, "xiaojian": 18}}} } 或者: { "name": "test", "score": {"xiaoming": 12, "xiaoli": {"xiaozhao": {"xiaoliu": 12, "xiaojian": [12,13,14]}}} }
第三步:查詢mongodb中的資料
1、查詢並序列化複雜json資料
serializers.py: class StudentSerializer(serializers.Serializer): name = serializers.CharField() score = serializers.DictField() # 序列化复杂的json数据 # DictField与EmbeddedDocumentField类似,但是比EmbeddedDocumentField更灵活 views.py: class FirstMongo4View(APIView): def get(self, request): student_info = Student3Model.objects.all() # 增加过滤条件 # student_info = Student3Model.objects.filter(name="test1") ser = StudentSerializer(instance=student_info, many=True) return Response(dict(msg="OK", code="10000", data=ser.data))
2.序列化mongodb中包含巢狀關係的兩個document
models.py: class AuthorModel(mongoengine.EmbeddedDocument): author_name = mongoengine.StringField(max_length=32) age = mongoengine.IntField() class BookModel(mongoengine.Document): book_name = mongoengine.StringField(max_length=64) publish = mongoengine.DateTimeField(default=datetime.datetime.utcnow()) words = mongoengine.IntField() author = mongoengine.EmbeddedDocumentField(AuthorModel) serializers.py: 序列化时注意与rest_framework的序列化中DictField()的区别 from rest_framework_mongoengine import serializers as s1 class AuthorSerializer(s1.DocumentSerializer): # DocumentSerializer继承自drf中的ModelSerializer,用于代替ModelSerializer序列化mongodb中的document. # 具体可以到官网上查看 class Meta: model = AuthorModel fields = ('author_name', 'age') class BookSerializer(s1.DocumentSerializer): author = AuthorSerializer() class Meta: model = BookModel fields = ('book_name', 'publish', 'words', 'author') AuthorSerializer还可以这样写: class AuthorSerializer(s1.EmbeddedDocumentSerializer): # EmbeddedDocumentSerializer继承了DocumentSerializer class Meta: model = AuthorModel fields = ('author_name', 'age') views.py: class BookView(APIView): def get(self, request): """ 查询数据 :param request: :return: """ books = BookModel.objects.all() ser = BookSerializer(instance=books, many=True) return Response(dict(msg="OK", code="10000", data=ser.data))
序列化mongodb中相關聯的兩個表時,如果序列化器繼承自rest_framework中的Serializer和ModelSerializer ,會拋出以下異常:
Django serialization to JSON error: 'MetaDict' object has no attribute 'concrete_model'
此時,序列化器需要繼承自rest_framework_mongoengine的類,具體可以查看官網:
http://umutbozkurt.github.io/...
以上是django開發之mongodb的設定與使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!