Discussion:
How to connect django rest-api with MongoDB
Sagar Bhadarka
2018-07-13 05:06:28 UTC
Permalink
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Felipe Rodrigues
2018-07-16 13:29:16 UTC
Permalink
Hello,

It is not a matter of connecting Django REST to MongoDB but connecting
Django itself. All of that logic is handled by it.



[image: --]
Felipe V. Rodrigues
[image: https://]felipevr.com
<https://felipevr.com>
Post by Sagar Bhadarka
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
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-16 15:48:48 UTC
Permalink
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.
Post by Felipe Rodrigues
Hello,
It is not a matter of connecting Django REST to MongoDB but connecting
Django itself. All of that logic is handled by it.
[image: --]
Felipe V. Rodrigues
[image: https://]felipevr.com
<https://felipevr.com>
Post by Sagar Bhadarka
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
.
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Mark Phillips
2018-07-16 22:35:47 UTC
Permalink
I am also interested in connecting Django to MongoDB for a project I am
working on.

Thanks!

Mark
Post by Felipe Rodrigues
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.
Post by Felipe Rodrigues
Hello,
It is not a matter of connecting Django REST to MongoDB but connecting
Django itself. All of that logic is handled by it.
[image: --]
Felipe V. Rodrigues
[image: https://]felipevr.com
<https://felipevr.com>
Post by Sagar Bhadarka
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
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
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Abhishek Jha
2018-07-16 22:36:34 UTC
Permalink
Will you guide me too

On Jul 17, 2018 4:05 AM, "Mark Phillips" <***@phillipsmarketing.biz> wrote:

I am also interested in connecting Django to MongoDB for a project I am
working on.

Thanks!

Mark
Post by Felipe Rodrigues
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.
Post by Felipe Rodrigues
Hello,
It is not a matter of connecting Django REST to MongoDB but connecting
Django itself. All of that logic is handled by it.
[image: --]
Felipe V. Rodrigues
[image: https://]felipevr.com
<https://felipevr.com>
Post by Sagar Bhadarka
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
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
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+***@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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Mark Phillips
2018-07-16 22:48:14 UTC
Permalink
Take a look at these:

http://blog.tomjohnhall.com/python-3-6-django-2-0-and-mongodb-3-4-3-6/

https://medium.freecodecamp.org/using-django-with-mongodb-by-adding-just-one-line-of-code-c386a298e179

haven't tried them yet, so ymmv.

Mark
Post by Abhishek Jha
Will you guide me too
I am also interested in connecting Django to MongoDB for a project I am
working on.
Thanks!
Mark
Post by Felipe Rodrigues
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.
Post by Felipe Rodrigues
Hello,
It is not a matter of connecting Django REST to MongoDB but connecting
Django itself. All of that logic is handled by it.
[image: --]
Felipe V. Rodrigues
[image: https://]felipevr.com
<https://felipevr.com>
Post by Sagar Bhadarka
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
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
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
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
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-17 09:51:28 UTC
Permalink
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?
Post by Mark Phillips
http://blog.tomjohnhall.com/python-3-6-django-2-0-and-mongodb-3-4-3-6/
https://medium.freecodecamp.org/using-django-with-mongodb-by-adding-just-one-line-of-code-c386a298e179
haven't tried them yet, so ymmv.
Mark
Post by Abhishek Jha
Will you guide me too
I am also interested in connecting Django to MongoDB for a project I am
working on.
Thanks!
Mark
Post by Felipe Rodrigues
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.
Post by Felipe Rodrigues
Hello,
It is not a matter of connecting Django REST to MongoDB but connecting
Django itself. All of that logic is handled by it.
[image: --]
Felipe V. Rodrigues
[image: https://]felipevr.com
<https://felipevr.com>
Post by Sagar Bhadarka
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
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
<javascript:>.
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
.
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
.
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Ola Tarkowska
2018-07-17 07:08:22 UTC
Permalink
Why not to use
https://github.com/umutbozkurt/django-rest-framework-mongoengine ? Works as
a charm for me
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Ola Tarkowska
2018-07-17 07:12:51 UTC
Permalink
For model just use http://mongoengine.org/
Post by Ola Tarkowska
Why not to use
https://github.com/umutbozkurt/django-rest-framework-mongoengine ? Works
as a charm for me
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-17 09:46:38 UTC
Permalink
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?
Post by Ola Tarkowska
Why not to use
https://github.com/umutbozkurt/django-rest-framework-mongoengine ? Works
as a charm for me
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Бурков Борис
2018-07-17 08:57:42 UTC
Permalink
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.
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-17 09:41:40 UTC
Permalink
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.
Post by Бурков Борис
If you're interested in using Django-REST-Framework-Mongoengine, you can
https://github.com/BurkovBA/django-rest-framework-mongoengine-example.
Nice to find out about this Djongo project, though.
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-07-19 09:56:22 UTC
Permalink
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
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-19 10:41:13 UTC
Permalink
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.
Post by Benjamin SOULAS
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
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-07-19 10:48:09 UTC
Permalink
Did you successfully make them working together? Do you have any examples
on github for example?

Kind regards
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-20 06:59:26 UTC
Permalink
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/
Post by Benjamin SOULAS
Did you successfully make them working together? Do you have any examples
on github for example?
Kind regards
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-07-20 12:54:11 UTC
Permalink
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
Post by Sagar Bhadarka
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/
Post by Benjamin SOULAS
Did you successfully make them working together? Do you have any examples
on github for example?
Kind regards
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-07-20 14:17:11 UTC
Permalink
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
Post by Sagar Bhadarka
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/
Post by Benjamin SOULAS
Did you successfully make them working together? Do you have any examples
on github for example?
Kind regards
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-23 07:08:19 UTC
Permalink
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?
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-07-23 07:52:17 UTC
Permalink
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
Post by Sagar Bhadarka
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?
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-23 08:46:59 UTC
Permalink
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
Post by Benjamin SOULAS
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
models.py
from django.db import models
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
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
"""
@brief List all products, or create a new product.
"""
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a product.
"""
wProducts = Product.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
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*
from djongo import models
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)
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
Post by Sagar Bhadarka
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?
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-07-23 09:42:36 UTC
Permalink
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 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)


@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
Post by Sagar Bhadarka
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
Post by Benjamin SOULAS
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
models.py
from django.db import models
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
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
"""
@brief List all products, or create a new product.
"""
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a product.
"""
wProducts = Product.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
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*
from djongo import models
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)
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
Post by Sagar Bhadarka
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?
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-07-23 11:03:17 UTC
Permalink
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'>
Post by Benjamin SOULAS
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
models.py
from djongo import models
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)
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
"""
@brief List all products, or create a new product.
"""
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a product.
"""
wProducts = Product.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
Product.delete()
return HttpResponse(status=204)
@csrf_exempt
"""
@brief List all products, or create a new channel.
"""
wChannels = Channel.objects.all()
wSerializer = ChannelSerializer(wChannels, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ChannelSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a channel.
"""
wChannel = Channel.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ChannelSerializer(wChannel)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ChannelSerializer(wChannel, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
Channel.delete()
return HttpResponse(status=204)
serializers.py
from rest_framework import serializers
from Api.models import Product, Channel
model = Channel
fields = ('sourceId', 'usageId', 'channelId', 'cabinetId', 'zoneId')
channels = ChannelSerializer(many=True)
model = Product
fields = ('dateCreation', 'dateUpdate', 'name', 'channels')
wChannels = validated_data.pop("channels")
wProduct = Product.objects.create(**validated_data)
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
Post by Sagar Bhadarka
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
Post by Benjamin SOULAS
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
models.py
from django.db import models
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
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
"""
@brief List all products, or create a new product.
"""
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a product.
"""
wProducts = Product.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
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
from djongo import models
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)
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
Post by Sagar Bhadarka
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?
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Sagar Bhadarka
2018-07-23 11:39:30 UTC
Permalink
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.
Post by Benjamin SOULAS
Internal Server Error: /products/
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
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'>
Post by Benjamin SOULAS
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
models.py
from djongo import models
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)
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
"""
@brief List all products, or create a new product.
"""
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a product.
"""
wProducts = Product.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
Product.delete()
return HttpResponse(status=204)
@csrf_exempt
"""
@brief List all products, or create a new channel.
"""
wChannels = Channel.objects.all()
wSerializer = ChannelSerializer(wChannels, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ChannelSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a channel.
"""
wChannel = Channel.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ChannelSerializer(wChannel)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ChannelSerializer(wChannel, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
Channel.delete()
return HttpResponse(status=204)
serializers.py
from rest_framework import serializers
from Api.models import Product, Channel
model = Channel
fields = ('sourceId', 'usageId', 'channelId', 'cabinetId', 'zoneId')
channels = ChannelSerializer(many=True)
model = Product
fields = ('dateCreation', 'dateUpdate', 'name', 'channels')
wChannels = validated_data.pop("channels")
wProduct = Product.objects.create(**validated_data)
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
Post by Sagar Bhadarka
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
Post by Benjamin SOULAS
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
models.py
from django.db import models
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
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
"""
@brief List all products, or create a new product.
"""
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a product.
"""
wProducts = Product.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
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
from djongo import models
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)
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
Post by Sagar Bhadarka
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?
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Benjamin SOULAS
2018-07-23 12:24:11 UTC
Permalink
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()
Post by Felipe Rodrigues
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.
Post by Benjamin SOULAS
Internal Server Error: /products/
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
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'>
Post by Benjamin SOULAS
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
models.py
from djongo import models
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)
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
"""
@brief List all products, or create a new product.
"""
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a product.
"""
wProducts = Product.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
Product.delete()
return HttpResponse(status=204)
@csrf_exempt
"""
@brief List all products, or create a new channel.
"""
wChannels = Channel.objects.all()
wSerializer = ChannelSerializer(wChannels, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ChannelSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a channel.
"""
wChannel = Channel.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ChannelSerializer(wChannel)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ChannelSerializer(wChannel, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
Channel.delete()
return HttpResponse(status=204)
serializers.py
from rest_framework import serializers
from Api.models import Product, Channel
model = Channel
fields = ('sourceId', 'usageId', 'channelId', 'cabinetId', 'zoneId')
channels = ChannelSerializer(many=True)
model = Product
fields = ('dateCreation', 'dateUpdate', 'name', 'channels')
wChannels = validated_data.pop("channels")
wProduct = Product.objects.create(**validated_data)
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
Post by Sagar Bhadarka
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
Post by Benjamin SOULAS
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
models.py
from django.db import models
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
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
"""
@brief List all products, or create a new product.
"""
wProducts = Product.objects.all()
wSerializer = ProductSerializer(wProducts, many=True)
return JsonResponse(wSerializer.data, safe=False)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(data=data)
wSerializer.save()
return JsonResponse(wSerializer.data, status=201)
return JsonResponse(wSerializer.errors, status=400)
@csrf_exempt
"""
@brief Retrieve, update or delete a product.
"""
wProducts = Product.objects.get(pk=pk)
return HttpResponse(status=404)
wSerializer = ProductSerializer(wProducts)
return JsonResponse(wSerializer.data)
data = JSONParser().parse(aRequest)
wSerializer = ProductSerializer(wProducts, data=data)
wSerializer.save()
return JsonResponse(wSerializer.data)
return JsonResponse(wSerializer.errors, status=400)
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
from djongo import models
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)
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
Post by Sagar Bhadarka
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?
--
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+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Loading...