'QuerySet' object has no attribute 'completed' - python

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

Related

Django POST Request 500 Error: AttributeError: 'QuerySet' object has no attribute '_meta'

I am trying to create a POST request to add a user to a database, but I am getting a 500 error with this message: AttributeError: 'QuerySet' object has no attribute '_meta'. Here is my code:
#api_view(['POST'])
def register(request):
data = request.data
if data['password'] != data['password_confirm']:
raise exceptions.APIException('Passwords do not match')
serializer = UserSerializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
UserSerializer:
from rest_framework import serializers
from users.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User.objects.all()
fields = ['id', 'first_name', 'last_name', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
User:
from django.db import models
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=63)
last_name = models.CharField(max_length=63)
email = models.CharField(max_length=255, unique=True)
password = models.CharField(max_length=255)
This is the stack trace:
Internal Server Error: /api/register
Traceback (most recent call last):
File "/home/amicharski/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/amicharski/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/amicharski/.local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/amicharski/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/decorators.py", line 50, in handler
return func(*args, **kwargs)
File "/home/amicharski/PycharmProjects/admin/users/views.py", line 16, in register
serializer.is_valid(raise_exception=True)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 220, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 419, in run_validation
value = self.to_internal_value(data)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 472, in to_internal_value
for field in fields:
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 355, in _writable_fields
for field in self.fields.values():
File "/home/amicharski/.local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 349, in fields
for key, value in self.get_fields().items():
File "/usr/local/lib/python3.8/dist-packages/rest_framework/serializers.py", line 1028, in get_fields
info = model_meta.get_field_info(model)
File "/usr/local/lib/python3.8/dist-packages/rest_framework/utils/model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'QuerySet' object has no attribute '_meta'
These are the kinds of errors that take 8 hours to solve but the solution is to change 1 line of code. I just had to shorten User.objects.all() in serializers.py on line 8 just to User, so line 8 is now: model = User.

Django rest framework's StringRelatedField is throwing KeyError

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

TypeError: Direct assignment to the reverse side of a related set is prohibited. Use thumbnails.set() instead

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.

int() argument must be a string, a bytes-like object or a number, not 'set'

I am not able to set up an ArrayReferenceField in Django using Djongo as the Engine. I am trying to build a Database which stores Projects of a student with the skills related to build that Project using ArrayReferenceField. The Form is generated through the Admin Page but in clicking save the following error is generated. This is the image of the input I give on the django admin page
TypeError: int() argument must be a string, a bytes-like object or a number, not 'set'
I looked into similar questions and none of them were able to answer my question. I even tried using ManyToManyField instead of it and it gives the same error.Can somebody help me with It. Thanks in advance.
myapp/models.py
enter code here
class Skill(models.Model):
id = models.AutoField(primary_key = True)
skills = models.CharField(max_length = 30)
def __str__(self):
return self.skills
class UserCredential(models.Model):
first_name = models.CharField(max_length = 25)
last_name = models.CharField(max_length = 25)
email = models.EmailField()
username = models.CharField(max_length = 50, unique = True)
password = models.CharField(max_length = 25)
skills = models.ArrayReferenceField(to=Skill ,
on_delete=models.CASCADE)
class Project(models.Model):
title = models.CharField(max_length = 100)
user = models.ForeignKey(to=UserCredential ,
on_delete=models.CASCADE)
description = models.TextField()
req_skills = models.ArrayReferenceField(to=Skill ,
on_delete=models.CASCADE)
myapp/serializers.py
class ProjectSerializer(serializers.ModelSerializer):
model = Project
fields = "__all__"
class Meta:
ordering = ["title"]
class SkillSerializer(serializers.ModelSerializer):
model = Skill
fields = ('skills',)
myapp/views.py
class UserCredentialListCreateView(generics.ListCreateAPIView):
queryset = UserCredential.objects.all()
serializer_class = UserCredentialSerializer
permission_classes = (IsAdminUser,)
class ProjectListCreateView(generics.ListCreateAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
permission_classes = (IsAdminUser,)
class SkillListCreateView(generics.ListCreateAPIView):
queryset = Skill.objects.all()
serializer_class = SkillSerializer
permission_classes = (IsAdminUser,)
Entire TraceBack:
Traceback (most recent call last):
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\contrib\admin\options.py", line 604, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\contrib\admin\options.py", line 1636, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\contrib\admin\options.py", line 1525, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\contrib\admin\options.py", line 1557, in _changeform_view
form_validated = form.is_valid()
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\forms\forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\forms\forms.py", line 180, in errors
self.full_clean()
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\forms\forms.py", line 383, in full_clean
self._post_clean()
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\forms\models.py", line 403, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\base.py", line 1130, in full_clean
self.clean_fields(exclude=exclude)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\base.py", line 1172, in clean_fields
setattr(self, f.attname, f.clean(raw_value, self))
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\fields\__init__.py", line 631, in clean
self.validate(value, model_instance)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\fields\related.py", line 903, in validate
**{self.remote_field.field_name: value}
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\query.py", line 844, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\query.py", line 862, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\sql\query.py", line 1263, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\sql\query.py", line 1287, in _add_q
split_subq=split_subq,
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\sql\query.py", line 1225, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\sql\query.py", line 1096, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\Bharat\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1.1-py3.6.egg\django\db\models\fields\__init__.py", line 965, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'set'

How to get just one field from a reverse reference in Django Rest Framework

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.

Categories

Resources