How to connect django rest-api with MongoDB

1,478 views
Skip to first unread message

Sagar Bhadarka

unread,
Jul 13, 2018, 1:06:28 AM7/13/18
to Django REST framework
Hi everyone, I'm complete beginner to Django and I want to connect Django rest-api to MongoDB. I saw examples on google but the examples that I found were to old and they used older version of Django, MongoDB and mongo-engine. Currently I'm using Django2.0.7, MongoDB3.2.20, and mongo-engine0.15 and I didn't find example with this version. I'm trying to do in  a way how they saw in older versions but it is not working. Even they mentioned in their articles and videos that syntax to connect MongoDB with Django is little different for new versions. Can anyone help me with this?

Felipe Rodrigues

unread,
Jul 16, 2018, 9:29:59 AM7/16/18
to django-res...@googlegroups.com
Hello,

It is not a matter of connecting Django REST to MongoDB but connecting Django itself. All of that logic is handled by it.
On Fri, Jul 13, 2018 at 2:06 AM, Sagar Bhadarka <sagar.w...@gmail.com> wrote:
Hi everyone, I'm complete beginner to Django and I want to connect Django rest-api to MongoDB. I saw examples on google but the examples that I found were to old and they used older version of Django, MongoDB and mongo-engine. Currently I'm using Django2.0.7, MongoDB3.2.20, and mongo-engine0.15 and I didn't find example with this version. I'm trying to do in  a way how they saw in older versions but it is not working. Even they mentioned in their articles and videos that syntax to connect MongoDB with Django is little different for new versions. Can anyone help me with this?

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Sagar Bhadarka

unread,
Jul 16, 2018, 11:48:48 AM7/16/18
to Django REST framework
Hello,
Do you know how to connect Django with MongoDB? can you share some code sample?
If you want I can share my code sample here. So let me know if you have experience with Django and MongoDB.

Mark Phillips

unread,
Jul 16, 2018, 6:35:51 PM7/16/18
to django-rest users
I am also interested in connecting Django to MongoDB for a project I am working on. 

Thanks!

Mark

To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsubscri...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Abhishek Jha

unread,
Jul 16, 2018, 6:36:50 PM7/16/18
to django-res...@googlegroups.com
Will you guide me too

On Jul 17, 2018 4:05 AM, "Mark Phillips" <ma...@phillipsmarketing.biz> wrote:
I am also interested in connecting Django to MongoDB for a project I am working on. 

Thanks!

Mark
On Mon, Jul 16, 2018 at 8:48 AM, Sagar Bhadarka <sagar.w...@gmail.com> wrote:
Hello,
Do you know how to connect Django with MongoDB? can you share some code sample?
If you want I can share my code sample here. So let me know if you have experience with Django and MongoDB.

On Monday, July 16, 2018 at 6:59:59 PM UTC+5:30, Felipe Rodrigues wrote:
Hello,

It is not a matter of connecting Django REST to MongoDB but connecting Django itself. All of that logic is handled by it.
On Fri, Jul 13, 2018 at 2:06 AM, Sagar Bhadarka <sagar.w...@gmail.com> wrote:
Hi everyone, I'm complete beginner to Django and I want to connect Django rest-api to MongoDB. I saw examples on google but the examples that I found were to old and they used older version of Django, MongoDB and mongo-engine. Currently I'm using Django2.0.7, MongoDB3.2.20, and mongo-engine0.15 and I didn't find example with this version. I'm trying to do in  a way how they saw in older versions but it is not working. Even they mentioned in their articles and videos that syntax to connect MongoDB with Django is little different for new versions. Can anyone help me with this?

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.

Mark Phillips

unread,
Jul 16, 2018, 6:48:17 PM7/16/18
to django-rest users

On Mon, Jul 16, 2018 at 3:36 PM, Abhishek Jha <jhaabhi...@gmail.com> wrote:
Will you guide me too
On Jul 17, 2018 4:05 AM, "Mark Phillips" <ma...@phillipsmarketing.biz> wrote:
I am also interested in connecting Django to MongoDB for a project I am working on. 

Thanks!

Mark
On Mon, Jul 16, 2018 at 8:48 AM, Sagar Bhadarka <sagar.w...@gmail.com> wrote:
Hello,
Do you know how to connect Django with MongoDB? can you share some code sample?
If you want I can share my code sample here. So let me know if you have experience with Django and MongoDB.

On Monday, July 16, 2018 at 6:59:59 PM UTC+5:30, Felipe Rodrigues wrote:
Hello,

It is not a matter of connecting Django REST to MongoDB but connecting Django itself. All of that logic is handled by it.
On Fri, Jul 13, 2018 at 2:06 AM, Sagar Bhadarka <sagar.w...@gmail.com> wrote:
Hi everyone, I'm complete beginner to Django and I want to connect Django rest-api to MongoDB. I saw examples on google but the examples that I found were to old and they used older version of Django, MongoDB and mongo-engine. Currently I'm using Django2.0.7, MongoDB3.2.20, and mongo-engine0.15 and I didn't find example with this version. I'm trying to do in  a way how they saw in older versions but it is not working. Even they mentioned in their articles and videos that syntax to connect MongoDB with Django is little different for new versions. Can anyone help me with this?

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

Ola Tarkowska

unread,
Jul 17, 2018, 3:08:22 AM7/17/18
to Django REST framework

Ola Tarkowska

unread,
Jul 17, 2018, 3:12:51 AM7/17/18
to Django REST framework
For model just use http://mongoengine.org/

Бурков Борис

unread,
Jul 17, 2018, 4:57:42 AM7/17/18
to Django REST framework
If you're interested in using Django-REST-Framework-Mongoengine, you can take a look at this example: https://github.com/BurkovBA/django-rest-framework-mongoengine-example.

Nice to find out about this Djongo project, though.

Sagar Bhadarka

unread,
Jul 17, 2018, 5:41:40 AM7/17/18
to Django REST framework
Hi
I already look into that example that you mentioned. Actually I looked into every example that everyone mentioned here in reply's. But problem is none of them worked for me. The example that you mentioned was working perfectly for the versions they mentioned in the requirement.txt file. I test that. But for new versions that I'm running in currently is not working. djongo starts working. I just connect my api with mongodb using djongo. But still if you know how to connect api which built using new version of django and new version of mongoengine with mongodb then please post update here.

Sagar Bhadarka

unread,
Jul 17, 2018, 5:46:38 AM7/17/18
to Django REST framework

Hi
I went through the link that you shared. I download the zip file and went through the code. But i didn't find code to make connection with mongodb. can you share the connection code here or can you tell where it's located? I didn't saw any settings.py file in that example. If there is no settings.py file then where they define connection code?

Sagar Bhadarka

unread,
Jul 17, 2018, 5:51:28 AM7/17/18
to Django REST framework
Hello
This djongo example works. I successfully connected django with mongodb. But do you have any experience for how to write code for serializers and views? I mean to say is it same how we write when we use mongoengine or is there any difference?

Benjamin SOULAS

unread,
Jul 19, 2018, 5:56:22 AM7/19/18
to Django REST framework
Hello everyone, 

Apparently Djongo does the job because it uses the Django ORM (in fact it implements it), so I think it could be a good choice, but it is possible to use django-rest-framework + djongo +  mongoDB? I mean, I am a little bit confused for modelling handling, someone tries? Do you use Djongo models inside django-rest-framework models to insert/retrieve documents? Maybe a stupid question? ^^

Kind regards

Sagar Bhadarka

unread,
Jul 19, 2018, 6:41:13 AM7/19/18
to Django REST framework
Hi,
Don't worry, no question is stupid. Yes I have insert documents in mongodb using django rest-api and djongo. Though I am not some expert. Currently I'm learning and implementing stuff.

Benjamin SOULAS

unread,
Jul 19, 2018, 6:48:09 AM7/19/18
to Django REST framework
Did you successfully make them working together? Do you have any examples on github for example?

Kind regards

Sagar Bhadarka

unread,
Jul 20, 2018, 2:59:26 AM7/20/18
to Django REST framework
Hi Benjamin,
As I said, I stored data in mongodb using django and djongo. Here is the github link. Hope it will helpful.
https://nesdis.github.io/djongo/get-started/

Benjamin SOULAS

unread,
Jul 20, 2018, 8:54:11 AM7/20/18
to Django REST framework
Hi Sagar,

I just find out how to do this, I misunderstood I was just needed to set the "djongo" db engine and it does the rest, I will take a look on your repos, thx a lot.

Kind regards

Benjamin SOULAS

unread,
Jul 20, 2018, 10:17:11 AM7/20/18
to Django REST framework
In fact, maybe I was not clear about the stack I want to use. So I want to use DRF AND "djongo" for mongoDB engine. My problem is first I started using DRF syntax to use simple objects based on IntegerField and CharField, it works on creating and retrieving data to/from mongo.

Now, I want to create a much complicated object, eg: a Product object that also contain a list of Channel objects, but in DRF I don't understand how to figure it ou BUT in djongo, ArrayFields exists, but i dont know if in DRF API code in should.can use those djongo object/models.

I hope it was much simpler to understand.

Kind regards.

Benjamin


Le vendredi 20 juillet 2018 08:59:26 UTC+2, Sagar Bhadarka a écrit :

Sagar Bhadarka

unread,
Jul 23, 2018, 3:08:19 AM7/23/18
to Django REST framework
I think what are you trying to say that you want to create embeded document. Something like relation mapping that you do in SQL database. Correct me If I am wrong. If you can give me a simple example for what are you want to do then I can help you?

Benjamin SOULAS

unread,
Jul 23, 2018, 3:52:17 AM7/23/18
to Django REST framework
Hi Sagar,

Ok let's try this. So I have a model named Product in which I got several attributes (eg: 3 simple like IntegerField or CharField), but I also want to add an attribute "channel" that represents a list of Channel objects. 

First of all, I implemented DRF with djongo as database Engine with only the 3 simple attributes below. which gives this:
models.py
from django.db import models

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")

serializers.py
from rest_framework import serializers

from Api.models import Product, Channel


class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('dateCreation', 'dateUpdate', 'name')

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)

urls.py
from django.conf.urls import url

from Api import views

urlpatterns = [
url(r'^products/$', views.ProductList),
url(r'^products/(?P<pk>[0-9]+)/$', views.ProductDetail)
]


But now my main problem is to know how to integrate an object as an attribute, and I watched several examples and now from nsdis djongo doc I finally got this (I thought I had to use djongo models for this):

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.ManyToManyField(Channel)

To be honest, I imagine I can do the same in Django Rest Framework models, but also in DjOngo models, so I need advices to continue my app.

I Hope It will be clearer now

Kind regards

Sagar Bhadarka

unread,
Jul 23, 2018, 4:46:59 AM7/23/18
to Django REST framework
Hi Benjamin,
I went through your code. In the first model where you have only 1 model which is product. over there you import model from django, so how did you store data in mongodb. because if you want to store data in mongodb using djongo then you have to import model from djongo and that you are doing in the last block of code where you have 2 models channels and product.
In the second model where you defining that channels class, I think instead of that many to many field may be you can use Embeded field. Please refer to this link. I hope it is helpful.
https://github.com/nesdis/djongo/blob/master/docs/docs/get-started.md

Benjamin SOULAS

unread,
Jul 23, 2018, 5:42:36 AM7/23/18
to Django REST framework
Hi,

Well indeed in my first version I used django models, and the reason why it worked with simple attributes I think it is because the were simple and because the engine was defined into the settings, I dont know how but it did the job.

Now I changed my code to introduce EmbeddedField, But it does not work. Just in case, I use a Postman client to test my API, and I am wondering if the fact to use django serializers in my case is not the pb:

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,
)

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, Channel
from Api.serializers import ProductSerializer, ChannelSerializer
@csrf_exempt
def ChannelList(aRequest):
"""

@brief List all products, or create a new channel.
"""
if aRequest.method == 'GET':
wChannels = Channel.objects.all()
wSerializer = ChannelSerializer(wChannels, many=True)


return JsonResponse(wSerializer.data, safe=False)

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


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

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


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

@brief Retrieve, update or delete a channel.
"""
try:
wChannel = Channel.objects.get(pk=pk)
except Channel.DoesNotExist:

return HttpResponse(status=404)

if aRequest.method == 'GET':
        wSerializer = ChannelSerializer(wChannel)

return JsonResponse(wSerializer.data)

elif aRequest.method == 'PUT':
data = JSONParser().parse(aRequest)
        wSerializer = ChannelSerializer(wChannel, data=data)

if wSerializer.is_valid():
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)

elif aRequest.method == 'DELETE':
        Channel.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')


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

Just to clarify, we agree that in order to send infos of the creation/get of a product or product list, I have to implement DRF views and serializers right? 

I thought workflow was: -->JSON DATA --> DRF API --> DRF Views/serializers --> Djongo Models --> Pymongo commands --> MongoDB

Benjamin SOULAS

unread,
Jul 23, 2018, 7:03:17 AM7/23/18
to Django REST framework
I forgot to show the stacktrace:

Internal Server Error: /products/
Traceback (most recent call last):
  File "/home/soulasb/dev-tmp/POC/EmsDRFDjongo/venv-app/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/home/soulasb/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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 26, in create
    wProduct = Product.objects.create(**validated_data)
  File "/home/soulasb/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/venv-app/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert
    using=using, raw=raw)
  File "/home/soulasb/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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/dev-tmp/POC/EmsDRFDjongo/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'>

Sagar Bhadarka

unread,
Jul 23, 2018, 7:39:30 AM7/23/18
to Django REST framework
Hello,
Yes, you have to use serializers. Actually when you use djongo it uses all the features of django. I think you should add this line in your model.py

objects = models.DjongoManager()
It is like django manager. Try this and then see may be it can solve issue.

Benjamin SOULAS

unread,
Jul 23, 2018, 8:24:11 AM7/23/18
to Django REST framework
Unfortunately, It does not work, I tried to add your line only in the Product model, does not work, in both of my models, same result as:

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 31, 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'>
[23/Jul/2018 12:10:52] "POST /products/ HTTP/1.1" 500 154127

Should I make a migrate command? I don't know anywhere where to look for, weird to me, I even add a create method in my serializers for ChannelSerializers:

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")

        (print(Product.objects is not None))


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

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

return wProduct

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()
Reply all
Reply to author
Forward
0 new messages