I want to specify one of the table fields using serializers, but I get the following error
Error :
TypeError: answer() missing 2 required positional arguments: 'Poll' and 'Answers'
code : serializers.py
from rest_framework import serializers
from .models import Answers, Poll ,Options
from authUser.models import User
class pollSerializer(serializers.ModelSerializer):
class Meta:
model = Poll
fields = ["pollAnswer" ]
pollAnswer = serializers.SerializerMethodField(method_name="answer")
def answer(self , Options :Options , Poll:Poll , Answers :Answers ):
poll = Poll.objects.get(pk=Poll.pk)
polltype = poll["pollType"]
if polltype == 0 :
return Poll.pollAnswer
if polltype == 1:
options = Options.objects.filter(pollId=Poll.pk)
big = 0
oid = 0
for i in options:
if big < Answers.objects.filter(pollId=Poll.pk ,optionId=i.pk).count():
big = Answers.objects.filter(pollId=Poll.pk ,optionId=i.pk).count()
oid = i.pk
return oid
CodePudding user response:
As you can see in the documentation, a SerializerMethodField
needs a method that takes a single argument: the instance of the model to serialize.
The serializer method referred to by the method_name argument should accept a single argument (in addition to self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object.
So:
class pollSerializer(serializers.ModelSerializer):
class Meta:
model = Poll
fields = ["pollAnswer" ]
pollAnswer = serializers.SerializerMethodField(method_name="answer")
def answer(self, poll: Poll):
...
This method should return a value that can be serialized, I'm not sure you can return an object.
If you want the answer, you should return a string.