I have the following model classes.
class Categories(models.Model):
id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True)
business = models.ForeignKey(Business, related_name='category_business', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
class Meta:
unique_together = ('business', 'name')
class Menu(models.Model):
id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, unique=True)
business = models.ForeignKey(Business, related_name='menu_business', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
description = models.CharField(max_length=128)
category = models.ForeignKey(Categories, related_name='menus', on_delete=models.CASCADE)
price = models.IntegerField()
class Meta:
unique_together = ('business', 'name', 'category')
def __str__(self):
return '%s %s %s' % (self.name, self.price, self.description)
and I have imported these classes as following as they are located in a separate package
Categories = apps.get_model('business', 'Categories')
Menu = apps.get_model('business', 'Menu')
and this is my serializer class
class GetCategoriesSerializer(serializers.ModelSerializer):
menus = serializers.StringRelatedField(many=True)
class Meta:
model = Categories
fields = ('name', 'menus')
and views is
class GetCategories(generics.ListAPIView):
"""
Returns a list of businesses to the user. It'd read only and no authentication is needed
"""
permission_classes = [ReadOnly]
queryset = Categories.objects.values()
serializer_class = GetCategoriesSerializer
and url has the following
path('customer/<str:pk>/categories', GetCategories.as_view()),
I am getting the following error
Traceback (most recent call last):
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/generics.py", line 199, in get
return self.list(request, *args, **kwargs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/mixins.py", line 48, in list
return Response(serializer.data)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 760, in data
ret = super().data
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 678, in to_representation
self.child.to_representation(item) for item in iterable
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 678, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 516, in to_representation
attribute = field.get_attribute(instance)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/relations.py", line 529, in get_attribute
relationship = get_attribute(instance, self.source_attrs)
File "/Users/mymac/myapp/mytestapp/venv/lib/python3.7/site-packages/rest_framework/fields.py", line 92, in get_attribute
instance = instance[attr]
Exception Type: KeyError at /customer/85f44d20-f936-4940-8e15-01393e42c4a8/categories
Exception Value: 'menus'
I looked into the DRF example and this seems to be a simple thing to achieve.
https://www.django-rest-framework.org/api-guide/relations/#api-reference
But I am kind of stuck at this point. Am I doing anything wrong? Thanks in advance for any help.
You should've used the QuerySet instead of ValueQuerySet. That is use queryset = Categories.objects.all() instead of queryset = Categories.objects.values()
So change the queryset attribute of the view as,
class GetCategories(generics.ListAPIView):
permission_classes = [ReadOnly]
queryset = Categories.objects.all()
serializer_class = GetCategoriesSerializer
Related
In my quiz app, every user can have multiple attempts. My model setup is as follows:
class Quiz(models.Model):
title = models.CharField(max_length=15)
slug = models.SlugField(blank=True)
questions_count = models.IntegerField(default=0)
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
label = models.CharField(max_length=1000)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
answer = models.CharField(max_length=100)
is_correct = models.BooleanField('Correct answer', default=False)
class QuizTaker(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
correct_answers = models.IntegerField(default=0)
completed = models.BooleanField(default=False)
attempt_number = models.PositiveIntegerField(default=0)
I get the error in my serializer when I try to determine if a given quiz has been completed:
class MyQuizListSerializer(serializers.ModelSerializer):
questions_count = serializers.SerializerMethodField()
completed = serializers.SerializerMethodField()
progress = serializers.SerializerMethodField()
score = serializers.SerializerMethodField()
class Meta:
model = Quiz
fields = ['id', 'title', 'type_of_content', 'song', 'slug',
'questions_count', 'completed', 'score', 'progress']
read_only_fields = ['questions_count', 'completed', 'progress']
def get_completed(self, obj):
try:
quiztaker = QuizTaker.objects.filter(user=self.context['request'].user, quiz=obj)
for attempt in quiztaker:
return quiztaker.completed #the error comes from this line
except QuizTaker.DoesNotExist:
return None
Can anybody tell me why I am getting this error? I am filtering because the user can have multiple attempts, therefore I get a queryset, and therefore I must loop through it. The QuizTaker model does have a completed field, so what is the issue?
Here is the full traceback:
Traceback (most recent call last):
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\generics.py", line 199, in get
return self.list(request, *args, **kwargs)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\mixins.py", line 46, in list
return Response(serializer.data)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 760, in data
ret = super().data
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation
return [
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 678, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\mvren\miniconda3\envs\myRuEnv\lib\site-packages\rest_framework\fields.py", line 1905, in to_representation
return method(value)
File "C:\Users\mvren\OneDrive\Documents\Coding\Russki\mysite\quizzes\serializers.py", line 48, in get_completed
return quiztaker.completed
Exception Type: AttributeError at /quizzes/api/my-quizzes/Melissavr
Exception Value: 'QuerySet' object has no attribute 'completed'
Simple mistake, the quiztaker object is a QuerySet.
You should be using the attempt variable assigned in the for loop:
for attempt in quiztaker:
return attempt.completed #the error comes from this line
I'm trying to get my serializer to work but I've run into this error: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use thumbnails.set() instead. And I'm not sure how to fix it. I've tried googling the problem but only found this docs which I have no idea of how to implement in my code:
class YoutubeSnippetSerializer(serializers.ModelSerializer):
thumbnails = YoutubeThumbnailSerializer(many=True)
class Meta:
model = YoutubeSnippet
fields = ['publishedAt', 'channelId', 'title', 'thumbnails', 'channelTitle', 'liveBroadcastContent', 'publishTime']
def create(self, validated_data):
thumb_data = validated_data.pop("thumbnails")
snippet = YoutubeSnippet.objects.create(**validated_data)
YoutubeThumbnails.objects.create(snippet=snippet, size="default", **thumb_data.pop("default"))
YoutubeThumbnails.objects.create(snippet=snippet, size="medium", **thumb_data.pop("medium"))
YoutubeThumbnails.objects.create(snippet=snippet, size="high", **thumb_data.pop("high"))
return snippet
The problem arises when the thumbnails variable is added. (thumbnails = YoutubeThumbnailSerializer(many=True) & 'thumbnails')
Code:
class YoutubeVideoSerializer(serializers.ModelSerializer):
youtubeId = YoutubeIdSerializer(many=True)
snippet = YoutubeSnippetSerializer(many=True)
class Meta:
model = YoutubeVideo
fields = ['kind', 'etag', 'youtubeId', 'snippet']
def create(self, validated_data):
id_data = validated_data.pop("youtubeId")
snippet_data = validated_data.pop("snippet")
video = YoutubeVideo.objects.create(**validated_data)
for data in id_data:
YoutubeId.objects.create(youtubeVideo=video, **data)
for data in snippet_data:
YoutubeSnippet.objects.create(youtubeVideo=video, **data)
return video
class YoutubeThumbnailSerializer(serializers.ModelSerializer):
class Meta:
model = YoutubeThumbnails
fields = ['url', 'width', 'height']
Models:
class YoutubeVideo(models.Model):
kind = models.CharField(max_length=255, null=True)
etag = models.CharField(max_length=255, null=True)
class YoutubeSnippet(models.Model):
publishedAt = models.DateTimeField(null=True)
channelId = models.CharField(max_length=255, null=True)
title = models.CharField(max_length=1084, null=True)
channelTitle = models.CharField(max_length=255, null=True)
liveBroadcastContent = models.CharField(max_length=255, null=True)
publishTime = models.DateTimeField(null=True)
youtubeVideo = models.ForeignKey(YoutubeVideo, related_name='snippet', on_delete=models.CASCADE)
class YoutubeThumbnails(models.Model):
size = models.CharField(max_length=255, null=True)
url = models.URLField(null=True)
width = models.IntegerField(null=True)
height = models.IntegerField(null=True)
snippet = models.ForeignKey(YoutubeSnippet, related_name='thumbnails', on_delete=models.CASCADE)
I really hope someone can point me in the right direction I'm completely lost here.
Traceback:
Traceback (most recent call last):
File "Y:\interperters\Personal_website_server\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "Y:\interperters\Personal_website_server\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "Y:\interperters\Personal_website_server\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "Y:\interperters\Personal_website_server\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "Y:\interperters\Personal_website_server\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "Y:\interperters\Personal_website_server\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "Y:\interperters\Personal_website_server\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "Y:\interperters\Personal_website_server\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "Y:\interperters\Personal_website_server\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "Y:\interperters\Personal_website_server\lib\site-packages\rest_framework\decorators.py", line 50, in handler
return func(*args, **kwargs)
File "Y:\GitRepo\Personal_website_server\esfand_app\api\views.py", line 27, in create_video
serializer.save()
File "Y:\interperters\Personal_website_server\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "Y:\GitRepo\Personal_website_server\esfand_app\api\serializers.py", line 69, in create
YoutubeSnippet.objects.create(youtubeVideo=video, **data)
File "Y:\interperters\Personal_website_server\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "Y:\interperters\Personal_website_server\lib\site-packages\django\db\models\query.py", line 431, in create
obj = self.model(**kwargs)
File "Y:\interperters\Personal_website_server\lib\site-packages\django\db\models\base.py", line 495, in __init__
_setattr(self, prop, kwargs[prop])
File "Y:\interperters\Personal_website_server\lib\site-packages\django\db\models\fields\related_descriptors.py", line 546, in __set__
% self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use thumbnails.set() instead.
I have two models, Roundtrip and Tour, and another model called RoundtripTour where I can link those two models in a many-to-many fashion. I have made a rest service that returns a Tour instance and a list of all RoundtripTour instances through a reverse reference, and it works perfectly, but the service returns all fields from the RoundtripTour model, and I want to return only the field that references the Roundtrip model instance.
These are my models:
class Roundtrip(models.Model):
name = models.CharField(max_length=70, verbose_name=_('Name'))
code = models.CharField(max_length=8, verbose_name=_('Code'))
duration = models.IntegerField(verbose_name=_('Duration'))
description = models.TextField(verbose_name=_('Description'))
class Tour(models.Model):
name = models.CharField(max_length=70, verbose_name=_('Name'))
description = models.TextField(verbose_name=_('Description'))
is_own = models.BooleanField(default=True, verbose_name=_('Is own tour?'))
code = models.CharField(max_length=10, verbose_name=_('Code'))
class RoundtripTour(models.Model):
roundtrip = models.ForeignKey(Roundtrip, on_delete=models.PROTECT, related_name='tours', verbose_name=_('Roundtrip'))
tour = models.ForeignKey(Tour, on_delete=models.PROTECT, related_name='roundtrips', verbose_name=_('Tour'))
day = models.IntegerField(verbose_name=_('Day'))
This is my serializer:
class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer):
roundtrips = serializers.SerializerMethodField()
def get_roundtrips(self, instance):
queryset = [x.roundtrip for x in instance.roundtrips.all()]
return RoundtripSerializer(queryset, many=True, context=self.context).data
class Meta:
model = models.Tour
fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips')
This is my view:
class TourRoundtripsViewSet(viewsets.ModelViewSet):
queryset = models.Tour.objects.all()
serializer_class = serializers.TourRoundtripsSerializer
I would like the roundtrips reverser reference to return only the field roundtrip from the RoundtripTour model (roundtrip field of RoundtripTour model). Is that possible?
I made the changes suggested by #Ykh, but I get an error. This is the traceback:
Internal Server Error: /es/reservations_manager/roundtrips/1/composition
Traceback (most recent call last):
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/mixins.py", line 58, in retrieve
return Response(serializer.data)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 560, in data
ret = super(Serializer, self).data
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/fields.py", line 1855, in to_representation
return method(value)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/Intellibook/ReservationsManagerApp/serializers.py", line 191, in get_hotels
return HotelSerializer(queryset, many=True).data
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 765, in data
ret = super(ListSerializer, self).data
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation
self.child.to_representation(item) for item in iterable
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/serializers.py", line 527, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/rest_framework/relations.py", line 356, in to_representation
"the serializer." % self.__class__.__name__
AssertionError: `HyperlinkedRelatedField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.
[24/May/2018 14:23:52] "GET /es/reservations_manager/roundtrips/1/composition HTTP/1.1" 500 145268
class TourRoundtripsSerializer(serializers.HyperlinkedModelSerializer):
roundtrips = serializers.SerializerMethodField()
def get_roundtrips(self, instance):
queryset = [x.roundtrip for x in instance.roundtrips.all()]
return RoundtripSerializer(queryset, many=True, context=self.context).data
class Meta:
model = models.Tour
fields = ('id', 'name', 'description', 'is_own', 'code', 'roundtrips')
depth = 1
use SerializerMethodField to get whatever you want.
I have models with many-to-many relationships with a through model. I am trying to set up a DRF serializer to display this data, but I am getting an error message whenever I try to render the API.
# models.py - simplified
class Person(models.Model):
first_name = models.CharField(max_length=250)
last_name = models.CharField(max_length=250)
status = models.IntegerField(choices=STATUS_CHOICES)
village = models.ForeignKey(Village)
gender = models.IntegerField(choices=GENDER_CHOICES)
class Case(models.Model):
summary = models.TextField()
session = models.ForeignKey(Session, on_delete=models.CASCADE)
case_type = models.ForeignKey(CaseType)
court_type = models.IntegerField(choices=COURT_TYPES)
verdict = models.ForeignKey(Verdict)
litigants = models.ManyToManyField(Person, through='Litigant', related_name='litigants')
class Litigant(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
case = models.ForeignKey(Case, on_delete=models.CASCADE)
role = models.ForeignKey(Role)
fine = models.ForeignKey(Money, null=True, related_name='fine')
My serializers.py looks as such:
# serializers.py - simplified
class LitigantSerializer(FlexFieldsModelSerializer):
class Meta:
model = Litigant
fields = ('id', 'person', 'case', 'role', 'fine')
class CaseSerializer(FlexFieldsModelSerializer):
litigants = LitigantSerializer(many=True, read_only=True)
class Meta:
model = Case
fields = ('id', 'summary', 'session', 'case_type', 'court_type', 'verdict', 'litigants')
class PersonSerializer(FlexFieldsModelSerializer):
class Meta:
model = Person
fields = ('id','first_name', 'last_name', 'village', 'status', 'gender')
My views.py is:
# views.py - simplified.
class PersonViewSet(FlexFieldsModelViewSet):
queryset = Person.objects.all().order_by('village__name', 'last_name', 'first_name')
serializer_class = PersonSerializer
class CaseViewSet(FlexFieldsModelViewSet):
queryset = Case.objects.all().order_by('session__village__name', 'session__date', 'court_type')
serializer_class = CaseSerializer
class LitigantViewSet(FlexFieldsModelViewSet):
queryset = Litigant.objects.all().order_by('case__session__village__name', 'case__session__date', 'person__last_name',
'person__first_name')
serializer_class = LitigantSerializer
However, when I navigate to api/cases/ I receive the following error:
'Person' object has no attribute 'person'
I'm not sure why it is using 'person' as an identifier for the Person object, instead of its PK. Is there something I am missing here?
Here is the stack trace, as requested.
Traceback:
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/viewsets.py" in view
90. return self.dispatch(request, *args, **kwargs)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
489. response = self.handle_exception(exc)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/views.py" in handle_exception
449. self.raise_uncaught_exception(exc)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
486. response = handler(request, *args, **kwargs)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_flex_fields/views.py" in list
28. return super(FlexFieldsMixin, self).list(request, *args, **kwargs)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/mixins.py" in list
45. return self.get_paginated_response(serializer.data)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/serializers.py" in data
739. ret = super(ListSerializer, self).data
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/serializers.py" in data
263. self._data = self.to_representation(self.instance)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/serializers.py" in to_representation
657. self.child.to_representation(item) for item in iterable
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/serializers.py" in <listcomp>
657. self.child.to_representation(item) for item in iterable
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/serializers.py" in to_representation
501. ret[field.field_name] = field.to_representation(attribute)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/serializers.py" in to_representation
657. self.child.to_representation(item) for item in iterable
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/serializers.py" in <listcomp>
657. self.child.to_representation(item) for item in iterable
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/serializers.py" in to_representation
488. attribute = field.get_attribute(instance)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/relations.py" in get_attribute
179. return get_attribute(instance, self.source_attrs)
File "/home/vagrant/.virtualenvs/medievaldb/lib/python3.4/site-packages/rest_framework/fields.py" in get_attribute
103. instance = getattr(instance, attr)
Exception Type: AttributeError at /api/cases/
Exception Value: 'Person' object has no attribute 'person'
i am trying to get data from django server and get this error.
Internal Server Error: /data/site-info/
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "/Users/hco/PycharmProjects/tool/linyit/data/views.py", line 17, in site_info
Response(serializer.data)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 674, in data
ret = super(ListSerializer, self).data
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 239, in data
self._data = self.to_representation(self.instance)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 614, in to_representation
self.child.to_representation(item) for item in iterable
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 459, in to_representation
fields = self._readable_fields
File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 353, in _readable_fields
field for field in self.fields.values()
AttributeError: 'tuple' object has no attribute 'values'
my_app/urls.py:
urlpatterns = [
url(r'^site-info/$', site_info, name='site_info'),
]
my_app/models.py:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class SiteInfo(models.Model):
site_id = models.IntegerField(primary_key=True)
site_name = models.CharField(max_length=100, blank=True, null=True)
latitude = models.DecimalField(max_digits=18, decimal_places=15, blank=True, null=True)
longitude = models.DecimalField(max_digits=18, decimal_places=15, blank=True, null=True)
class Meta:
# managed = False
db_table = 'site_info'
data/views:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import SiteInfo
from .serializers import SiteInfoSerializer
# Create your views here.
#api_view(['GET', 'POST'])
def site_info(request):
"""
List all sites
"""
if request.method == 'GET':
sites = SiteInfo.objects.using('teldata').all()
serializer = SiteInfoSerializer(sites, many=True)
Response(serializer.data)
my_app/serializers:
from rest_framework import serializers
from .models import SiteInfo
class SiteInfoSerializer(serializers.ModelSerializer):
model = SiteInfo
fields = ('site_id', 'site_name', 'latitude', 'longitude')
what could be the problem? thanks
Your serializer needs to use a nested Meta class to declare model and fields (you were declaring them as normal attributes of the class instead of nesting them):
class SiteInfoSerializer(serializers.ModelSerializer):
class Meta:
model = SiteInfo
fields = ('site_id', 'site_name', 'latitude', 'longitude')
by adding (class Meta) in serializers.py the error can get solved as per my error which i were getting.
the image which shows code of serializers.py