将 djongo (Mongo ORM) 集成到 Django Rest 框架中

Posted

技术标签:

【中文标题】将 djongo (Mongo ORM) 集成到 Django Rest 框架中【英文标题】:Integrate djongo (Mongo ORM) into Django Rest Framework 【发布时间】:2019-01-01 01:04:42 【问题描述】:

实际上我正在开发一个 POC,我们想要一个具有 REST API 并在 Python 中与 MongoDB 讨论的应用程序。

为此,我们找到了一些技术,例如 API 端的 Django-rest-framework 和 ORM 端的 djongo。尽管如此,我浏览了很多关于如何在 DRF 中实现 djongo ORM 的 tutos,没有办法,但显然这是可能的,有人可以确认吗?

我的主要问题是我的 POC 绝对不起作用,确实,在我的 DRF 序列化器中使用的 djongo 模型中,但它根本不起作用,我不明白,有人能弄清楚这是怎么回事开?:

models.py:

from djongo import models


class Channel(models.Model):
    sourceId = models.IntegerField(default=-1)
    usageId = models.IntegerField(default=0)
    channelId = models.IntegerField(default=0)
    cabinetId = models.IntegerField(default=0)
    zoneId = models.IntegerField(default=0)


class Product(models.Model):
    dateCreation = models.DateTimeField(auto_now=True)
    dateUpdate = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=50, default="Unknown product name")
    channels = models.EmbeddedModelField(
        model_container=Channel,
    )

    objects = models.DjongoManager()

views.py:

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from Api.models import Product
from Api.serializers import ProductSerializer


@csrf_exempt
def ProductList(aRequest):
    """

    @brief List all products, or create a new product.
    """
    if aRequest.method == 'GET':
        wProducts = Product.objects.all()
        wSerializer = ProductSerializer(wProducts, many=True)

        return JsonResponse(wSerializer.data, safe=False)

    elif aRequest.method == 'POST':
        data = JSONParser().parse(aRequest)
        wSerializer = ProductSerializer(data=data)

        if wSerializer.is_valid():
            wSerializer.save()

            return JsonResponse(wSerializer.data, status=201)
        return JsonResponse(wSerializer.errors, status=400)


@csrf_exempt
def ProductDetail(aRequest, pk):
    """

    @brief Retrieve, update or delete a product.
    """
    try:
        wProducts = Product.objects.get(pk=pk)
    except Product.DoesNotExist:
        return HttpResponse(status=404)

    if aRequest.method == 'GET':
        wSerializer = ProductSerializer(wProducts)
        return JsonResponse(wSerializer.data)

    elif aRequest.method == 'PUT':
        data = JSONParser().parse(aRequest)
        wSerializer = ProductSerializer(wProducts, data=data)
        if wSerializer.is_valid():
            wSerializer.save()
            return JsonResponse(wSerializer.data)
        return JsonResponse(wSerializer.errors, status=400)

    elif aRequest.method == 'DELETE':
        Product.delete()
        return HttpResponse(status=204)

serializers.py:

from rest_framework import serializers

from Api.models import Product, Channel


class ChannelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Channel
        fields = ('sourceId', 'usageId', 'channelId', 'cabinetId', 'zoneId')

    def create(self, validated_data):

        wChannel = Channel.objects.create(**validated_data)

        return wChannel


class ProductSerializer(serializers.ModelSerializer):

    channels = ChannelSerializer(many=True)

    class Meta:
        model = Product
        fields = ('dateCreation', 'dateUpdate', 'name', 'channels')

    def create(self, validated_data):
        wChannels = validated_data.pop("channels")

        wProduct = Product.objects.create(**validated_data)

        for wChannel in wChannels:
            Channel.objects.create(product=wProduct, **wChannel)

        return wProduct

当我使用这个 POST 请求运行我的服务器时:


    "dateCreation": "2018-07-20 12:00:00.000",
    "dateUpdate": "2018-07-20 12:00:00.000",
    "name": "post_test_channel_1",
    "channels": [
        "sourceId": -1,
        "usageId": 100,
        "channelId": 0,
        "cabinetId": 0,
        "zoneId": 1
    ]

我获得了那个堆栈跟踪:

Internal Server Error: /products/
Traceback (most recent call last):
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/soulasb/projects/POC/PocEms/Api/views.py", line 25, in ProductList
    wSerializer.save()
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/rest_framework/serializers.py", line 214, in save
    self.instance = self.create(validated_data)
  File "/home/soulasb/projects/POC/PocEms/Api/serializers.py", line 29, in create
    wProduct = Product.objects.create(**validated_data)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert
    using=using, raw=raw)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1284, in execute_sql
    for sql, params in self.as_sql():
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1237, in as_sql
    for obj in self.query.objs
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1237, in <listcomp>
    for obj in self.query.objs
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1236, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1176, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 767, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "/home/soulasb/projects/POC/venv-app/lib/python3.6/site-packages/djongo/models/fields.py", line 461, in get_db_prep_value
    model=Model
ValueError: Value: None must be instance of Model: <class 'django.db.models.base.Model'>

【问题讨论】:

您找到了一个好的解决方案吗?在这里和那里也遇到问题...... 传递一个空的嵌入文档有问题吗? 【参考方案1】:

可能是在 settings.py 中将 ENFORCE_SCHEMA 设置为 true。也许将其更改为“ENFORCE_SCHEMA: false”。

【讨论】:

【参考方案2】:

当您在模型中添加了 EmbeddedModelField 并且在创建此模型的条目时未将对象传递给此字段时,通常会发生这种情况。 我没有找到使用 null=True 选项添加 EmbeddedModelField 的选项。

希望这对某人有所帮助

【讨论】:

以上是关于将 djongo (Mongo ORM) 集成到 Django Rest 框架中的主要内容,如果未能解决你的问题,请参考以下文章

如何将Django ORM连接到mongo atlas?

mongo_aggregate() 的 Djongo 映射器问题

djongo:Django和MongoDB连接器

使用Mongoose(ORM)将多个应用程序与一个mongo数据库连接

将遗留的 mySQL 数据库集成到新的 Django ORM 驱动的数据结构中

Djongo重新定义了ArrayModelField的结构