博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django开发-mongodb的配置与使用
阅读量:6613 次
发布时间:2019-06-24

本文共 5331 字,大约阅读时间需要 17 分钟。

今天整理了一下在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://nraso.baihongyu.com/

你可能感兴趣的文章
@html.ActionLink的几种参数格式
查看>>
IOC/AOP随笔目录
查看>>
小议解耦合--应用设计模式
查看>>
一个关于累加工资的T-SQL语句
查看>>
C++观察者模式
查看>>
HTTP 2.0 与 tomcat
查看>>
二、如何通过URL获取其他网页源代码内容(火狐插件扩展开发教程)
查看>>
2.2. nmtui
查看>>
SQL Server优化50法
查看>>
实现封装树节点拖拽操作的组件[原]
查看>>
微信小程序 开发 微信开发者工具 快捷键
查看>>
[LintCode] Toy Factory 玩具工厂
查看>>
自动ping博客服务程序
查看>>
HelloWorld 和相关设置
查看>>
《Using Flash Media Server Edge Servers》读后感
查看>>
【面试虐菜】—— JAVA面试题(1)
查看>>
/bin/bash^M: bad interpreter: 没有那个文件或目录
查看>>
html5和css3对移动设备和电脑浏览器支持列表
查看>>
linux的convert图片处理工具
查看>>
[LeetCode] My Calendar II 我的日历之二
查看>>