EmbeddedModelField not work with django_rest_framework
One line description of the issue
the seriliarzers with EmbeddedModelField will riase the following exception.
~/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/django/db/models/base.py in _get_pk_val(self, meta)
551 def _get_pk_val(self, meta=None):
552 meta = meta or self._meta
--> 553 return getattr(self, meta.pk.attname)
554
555 def _set_pk_val(self, value):
AttributeError: 'NoneType' object has no attribute 'attname'
Python script
# models.py
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
class Meta:
abstract = True
class Entry(models.Model):
blog = models.EmbeddedModelField(model_container=Blog)
headline = models.CharField(max_length=255)
# seriliazers.py
from rest_framework import serializers
from face import models
class EntrySerializer(serializers.ModelSerializer):
class Meta:
model = models.Entry
fields = ('pk', 'blog', 'headline')
# views.py
from rest_framework import viewsets
from face.seriliazers import EntrySerializer
from face.models import Entry
class EntryViewSet(viewsets.ModelViewSet):
"""entry api endpoint"""
queryset = Entry.objects.all().order_by('-pk')
serializer_class = EntrySerializer
# urls.py
from django.conf import settings
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from face import views
router = routers.DefaultRouter()
router.register(r'entry', views.EntryViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
path('^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path(r'__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
visit http://localhost:8000/entry/ in browser will raise exceptions
Traceback
the traceback
Internal Server Error: /entry/
Traceback (most recent call last):
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/mixins.py", line 48, in list
return Response(serializer.data)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/serializers.py", line 765, in data
ret = super(ListSerializer, self).data
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation
self.child.to_representation(item) for item in iterable
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/rest_framework/fields.py", line 1897, in to_representation
return self.model_field.value_to_string(obj)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 840, in value_to_string
return str(self.value_from_object(obj))
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/django/db/models/base.py", line 506, in __str__
return '%s object (%s)' % (self.__class__.__name__, self.pk)
File "/home/hackrole/.virtualenvs/face_rebuild_service-wOwN483t/lib/python3.6/site-packages/django/db/models/base.py", line 553, in _get_pk_val
return getattr(self, meta.pk.attname)
AttributeError: 'NoneType' object has no attribute 'attname'
so what the project status work with rest_framework, has it been supperted and tested?
I get the same issue when using EmbeddedModelField with Django Rest Framework.
Same issue here with same models on
Django 2.1.1
django-rest-framework 0.1.0
djangorestframework 3.8.2
djongo 1.2.30
pip 18.0
pymongo 3.7.1
pytz 2018.5
setuptools 39.1.0
sqlparse 0.2.4
after a little reading the source, this is happening because you didn't implement a __str__ method in your abstract model. You can add
def __str__(self):
return self.name
to your Blog model and it works. But i am not sure about is this a bug or something should you avoid.
I am also facing this problem
my model is
class A(models.Model):
img = models.TextField(null=True)
times = models.TextField(null=True)
min = models.TextField(null=True)
class Meta:
abstract = True
class B(models.Model):
feelToday = models.TextField(null=True)
dairyPic = models.EmbeddedModelField(model_container=A)
class Meta:
db_table = 'diary'
View
queryset = B.objects.all()
ser = BSerializer(queryset, many=True)
return Response({'details': ser.data})
Traceback
Traceback (most recent call last):
File "C:\Users\Nitish\Envs\py3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "D:\projects\face\diary\views.py", line 40, in get
return Response({'details': ser.data})
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\serializers.py", line 765, in data
ret = super(ListSerializer, self).data
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\serializers.py", line 683, in to_representation
self.child.to_representation(item) for item in iterable
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\serializers.py", line 683, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\serializers.py", line 527, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\rest_framework\fields.py", line 1935, in to_representation
return self.model_field.value_to_string(obj)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\django\db\models\fields\__init__.py", line 840, in value_to_string
return str(self.value_from_object(obj))
File "C:\Users\Nitish\Envs\py3\lib\site-packages\django\db\models\base.py", line 506, in __str__
return '%s object (%s)' % (self.__class__.__name__, self.pk)
File "C:\Users\Nitish\Envs\py3\lib\site-packages\django\db\models\base.py", line 553, in _get_pk_val
return getattr(self, meta.pk.attname)
AttributeError: 'NoneType' object has no attribute 'attname'
how to serialize this model
@lexygon @nesdis @hackrole
Can anyone explain how to best write ModelSerializers for djongo models containing an EmbeddedModelField or ArrayReferenceField?
Check my solution on the same issue: https://github.com/nesdis/djongo/issues/115#issuecomment-384910745
Issue has be solved in #115
after a little reading the source, this is happening because you didn't implement a
__str__method in your abstract model. You can adddef __str__(self): return self.nameto your Blog model and it works. But i am not sure about is this a bug or something should you avoid.
thanks man , you saved me couple of hours!
in some cases this will fix it also:
def __unicode__(self):
return self.title
after a little reading the source, this is happening because you didn't implement a
__str__method in your abstract model. You can adddef __str__(self): return self.nameto your Blog model and it works. But i am not sure about is this a bug or something should you avoid.
I tried doing this. When I try to add an entry via the admin, it does not save. Instead it gives an error saying - Value: John must be an instance of <class 'dict'> John is the value of the field 'name' in this example.
Is there a version of Django that I should be using. I know that the latest Django version doesn't support instantiation of abstract classes.