Creating serializer to display correct data












0















I have 4 models. User, Question, Choice, and Voting. This is basically a polls app I'm trying to create. A question can have many choices. The Voting model tracks what each user chose as their answer.



What I'd like to do is retrieve all the questions and also check what choice the logged in user selected for each question. Here's the models:



class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
status = models.CharField(max_length=200)
total_votes = models.IntegerField(default=0)

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice = models.CharField(max_length=120)
vote_count = models.IntegerField(default=0)

class Voting(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
choice = models.ForeignKey(Choice, on_delete=models.CASCADE)


Here's how I want the data displayed:



{
user: 2
status: "Hello"
total_votes: 101
choices: [
{
"id": 2,
"choice": "first choice",
"vote_count": 31,
"question": 3
},
{
"id": 4,
"choice": "second choice",
"vote_count": 70,
"question": 3
}
],
choice_selected: 2
}


In the data above, the logged in user selected choice 2 in this specific question.



Edit: My attempt to add serializer, but displays Object of type 'Voting' is not JSON serializable



class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = '__all__'

class QuestionSerializer(serializers.ModelSerializer):
choices = ChoiceSerializer(source='choice_set', many=True)
class Meta:
model = Question
fields = '__all__'


class GetProfileQuestions(ListAPIView):
serializer_class = QuestionSerializer

def get_queryset(self):
return Question.objects.all()


This query successfully prints out each question and its choices. However, how do I make it so that it also prints out which choice the user selected for each question?



class VotingSerializer(serializers.ModelSerializer):

class Meta:
model = Voting
fields = '__all__'


class ChoiceSerializer(serializers.ModelSerializer):
votes = VotingSerializer(source='voting_set', many=True)
class Meta:
model = Choice
fields = '__all__'


class QuestionSerializer(serializers.ModelSerializer):
choices = ChoiceSerializer(source='choice_set', many=True)
choice_selected = serializers.SerializerMethodField()
class Meta:
model = Question
fields = '__all__'

def get_choice_selected(self, obj):
choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
return choice_selected









share|improve this question





























    0















    I have 4 models. User, Question, Choice, and Voting. This is basically a polls app I'm trying to create. A question can have many choices. The Voting model tracks what each user chose as their answer.



    What I'd like to do is retrieve all the questions and also check what choice the logged in user selected for each question. Here's the models:



    class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    status = models.CharField(max_length=200)
    total_votes = models.IntegerField(default=0)

    class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice = models.CharField(max_length=120)
    vote_count = models.IntegerField(default=0)

    class Voting(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    choice = models.ForeignKey(Choice, on_delete=models.CASCADE)


    Here's how I want the data displayed:



    {
    user: 2
    status: "Hello"
    total_votes: 101
    choices: [
    {
    "id": 2,
    "choice": "first choice",
    "vote_count": 31,
    "question": 3
    },
    {
    "id": 4,
    "choice": "second choice",
    "vote_count": 70,
    "question": 3
    }
    ],
    choice_selected: 2
    }


    In the data above, the logged in user selected choice 2 in this specific question.



    Edit: My attempt to add serializer, but displays Object of type 'Voting' is not JSON serializable



    class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
    model = Choice
    fields = '__all__'

    class QuestionSerializer(serializers.ModelSerializer):
    choices = ChoiceSerializer(source='choice_set', many=True)
    class Meta:
    model = Question
    fields = '__all__'


    class GetProfileQuestions(ListAPIView):
    serializer_class = QuestionSerializer

    def get_queryset(self):
    return Question.objects.all()


    This query successfully prints out each question and its choices. However, how do I make it so that it also prints out which choice the user selected for each question?



    class VotingSerializer(serializers.ModelSerializer):

    class Meta:
    model = Voting
    fields = '__all__'


    class ChoiceSerializer(serializers.ModelSerializer):
    votes = VotingSerializer(source='voting_set', many=True)
    class Meta:
    model = Choice
    fields = '__all__'


    class QuestionSerializer(serializers.ModelSerializer):
    choices = ChoiceSerializer(source='choice_set', many=True)
    choice_selected = serializers.SerializerMethodField()
    class Meta:
    model = Question
    fields = '__all__'

    def get_choice_selected(self, obj):
    choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
    return choice_selected









    share|improve this question



























      0












      0








      0








      I have 4 models. User, Question, Choice, and Voting. This is basically a polls app I'm trying to create. A question can have many choices. The Voting model tracks what each user chose as their answer.



      What I'd like to do is retrieve all the questions and also check what choice the logged in user selected for each question. Here's the models:



      class Question(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      status = models.CharField(max_length=200)
      total_votes = models.IntegerField(default=0)

      class Choice(models.Model):
      question = models.ForeignKey(Question, on_delete=models.CASCADE)
      choice = models.CharField(max_length=120)
      vote_count = models.IntegerField(default=0)

      class Voting(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      choice = models.ForeignKey(Choice, on_delete=models.CASCADE)


      Here's how I want the data displayed:



      {
      user: 2
      status: "Hello"
      total_votes: 101
      choices: [
      {
      "id": 2,
      "choice": "first choice",
      "vote_count": 31,
      "question": 3
      },
      {
      "id": 4,
      "choice": "second choice",
      "vote_count": 70,
      "question": 3
      }
      ],
      choice_selected: 2
      }


      In the data above, the logged in user selected choice 2 in this specific question.



      Edit: My attempt to add serializer, but displays Object of type 'Voting' is not JSON serializable



      class ChoiceSerializer(serializers.ModelSerializer):
      class Meta:
      model = Choice
      fields = '__all__'

      class QuestionSerializer(serializers.ModelSerializer):
      choices = ChoiceSerializer(source='choice_set', many=True)
      class Meta:
      model = Question
      fields = '__all__'


      class GetProfileQuestions(ListAPIView):
      serializer_class = QuestionSerializer

      def get_queryset(self):
      return Question.objects.all()


      This query successfully prints out each question and its choices. However, how do I make it so that it also prints out which choice the user selected for each question?



      class VotingSerializer(serializers.ModelSerializer):

      class Meta:
      model = Voting
      fields = '__all__'


      class ChoiceSerializer(serializers.ModelSerializer):
      votes = VotingSerializer(source='voting_set', many=True)
      class Meta:
      model = Choice
      fields = '__all__'


      class QuestionSerializer(serializers.ModelSerializer):
      choices = ChoiceSerializer(source='choice_set', many=True)
      choice_selected = serializers.SerializerMethodField()
      class Meta:
      model = Question
      fields = '__all__'

      def get_choice_selected(self, obj):
      choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
      return choice_selected









      share|improve this question
















      I have 4 models. User, Question, Choice, and Voting. This is basically a polls app I'm trying to create. A question can have many choices. The Voting model tracks what each user chose as their answer.



      What I'd like to do is retrieve all the questions and also check what choice the logged in user selected for each question. Here's the models:



      class Question(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      status = models.CharField(max_length=200)
      total_votes = models.IntegerField(default=0)

      class Choice(models.Model):
      question = models.ForeignKey(Question, on_delete=models.CASCADE)
      choice = models.CharField(max_length=120)
      vote_count = models.IntegerField(default=0)

      class Voting(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      choice = models.ForeignKey(Choice, on_delete=models.CASCADE)


      Here's how I want the data displayed:



      {
      user: 2
      status: "Hello"
      total_votes: 101
      choices: [
      {
      "id": 2,
      "choice": "first choice",
      "vote_count": 31,
      "question": 3
      },
      {
      "id": 4,
      "choice": "second choice",
      "vote_count": 70,
      "question": 3
      }
      ],
      choice_selected: 2
      }


      In the data above, the logged in user selected choice 2 in this specific question.



      Edit: My attempt to add serializer, but displays Object of type 'Voting' is not JSON serializable



      class ChoiceSerializer(serializers.ModelSerializer):
      class Meta:
      model = Choice
      fields = '__all__'

      class QuestionSerializer(serializers.ModelSerializer):
      choices = ChoiceSerializer(source='choice_set', many=True)
      class Meta:
      model = Question
      fields = '__all__'


      class GetProfileQuestions(ListAPIView):
      serializer_class = QuestionSerializer

      def get_queryset(self):
      return Question.objects.all()


      This query successfully prints out each question and its choices. However, how do I make it so that it also prints out which choice the user selected for each question?



      class VotingSerializer(serializers.ModelSerializer):

      class Meta:
      model = Voting
      fields = '__all__'


      class ChoiceSerializer(serializers.ModelSerializer):
      votes = VotingSerializer(source='voting_set', many=True)
      class Meta:
      model = Choice
      fields = '__all__'


      class QuestionSerializer(serializers.ModelSerializer):
      choices = ChoiceSerializer(source='choice_set', many=True)
      choice_selected = serializers.SerializerMethodField()
      class Meta:
      model = Question
      fields = '__all__'

      def get_choice_selected(self, obj):
      choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
      return choice_selected






      python django django-rest-framework django-queryset






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 6:04









      Red Cricket

      4,551103388




      4,551103388










      asked Nov 20 '18 at 23:49









      user2896120user2896120

      1,0121128




      1,0121128
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I think you will want this in your QuestionSerializer class



           choice_selected = serializers.SerializerMethodField()


          and define a method that looks something like this in QuestionSerializer …



          def get_choice_selected(self, obj):
          choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
          return choice_selected


          The above is untested.






          share|improve this answer
























          • Hmm, I am getting this error: Object of type 'Voting' is not JSON serializable

            – user2896120
            Nov 21 '18 at 3:57











          • Add a serializer for it then.

            – Red Cricket
            Nov 21 '18 at 4:05











          • How would you do it in this situation? I am not too familiar with functions inside serializers

            – user2896120
            Nov 21 '18 at 4:11











          • I would add a serializer class like you have for ChoiceSerializer but the class name would be VotingSerializer and it would have Model = Voting

            – Red Cricket
            Nov 21 '18 at 5:52













          • Hmm, I did that but I am getting the same error. I added what I did in my question please take a look at the edits see if I'm doing it correctly?

            – user2896120
            Nov 21 '18 at 5:59











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403329%2fcreating-serializer-to-display-correct-data%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          I think you will want this in your QuestionSerializer class



           choice_selected = serializers.SerializerMethodField()


          and define a method that looks something like this in QuestionSerializer …



          def get_choice_selected(self, obj):
          choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
          return choice_selected


          The above is untested.






          share|improve this answer
























          • Hmm, I am getting this error: Object of type 'Voting' is not JSON serializable

            – user2896120
            Nov 21 '18 at 3:57











          • Add a serializer for it then.

            – Red Cricket
            Nov 21 '18 at 4:05











          • How would you do it in this situation? I am not too familiar with functions inside serializers

            – user2896120
            Nov 21 '18 at 4:11











          • I would add a serializer class like you have for ChoiceSerializer but the class name would be VotingSerializer and it would have Model = Voting

            – Red Cricket
            Nov 21 '18 at 5:52













          • Hmm, I did that but I am getting the same error. I added what I did in my question please take a look at the edits see if I'm doing it correctly?

            – user2896120
            Nov 21 '18 at 5:59
















          0














          I think you will want this in your QuestionSerializer class



           choice_selected = serializers.SerializerMethodField()


          and define a method that looks something like this in QuestionSerializer …



          def get_choice_selected(self, obj):
          choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
          return choice_selected


          The above is untested.






          share|improve this answer
























          • Hmm, I am getting this error: Object of type 'Voting' is not JSON serializable

            – user2896120
            Nov 21 '18 at 3:57











          • Add a serializer for it then.

            – Red Cricket
            Nov 21 '18 at 4:05











          • How would you do it in this situation? I am not too familiar with functions inside serializers

            – user2896120
            Nov 21 '18 at 4:11











          • I would add a serializer class like you have for ChoiceSerializer but the class name would be VotingSerializer and it would have Model = Voting

            – Red Cricket
            Nov 21 '18 at 5:52













          • Hmm, I did that but I am getting the same error. I added what I did in my question please take a look at the edits see if I'm doing it correctly?

            – user2896120
            Nov 21 '18 at 5:59














          0












          0








          0







          I think you will want this in your QuestionSerializer class



           choice_selected = serializers.SerializerMethodField()


          and define a method that looks something like this in QuestionSerializer …



          def get_choice_selected(self, obj):
          choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
          return choice_selected


          The above is untested.






          share|improve this answer













          I think you will want this in your QuestionSerializer class



           choice_selected = serializers.SerializerMethodField()


          and define a method that looks something like this in QuestionSerializer …



          def get_choice_selected(self, obj):
          choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
          return choice_selected


          The above is untested.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 0:11









          Red CricketRed Cricket

          4,551103388




          4,551103388













          • Hmm, I am getting this error: Object of type 'Voting' is not JSON serializable

            – user2896120
            Nov 21 '18 at 3:57











          • Add a serializer for it then.

            – Red Cricket
            Nov 21 '18 at 4:05











          • How would you do it in this situation? I am not too familiar with functions inside serializers

            – user2896120
            Nov 21 '18 at 4:11











          • I would add a serializer class like you have for ChoiceSerializer but the class name would be VotingSerializer and it would have Model = Voting

            – Red Cricket
            Nov 21 '18 at 5:52













          • Hmm, I did that but I am getting the same error. I added what I did in my question please take a look at the edits see if I'm doing it correctly?

            – user2896120
            Nov 21 '18 at 5:59



















          • Hmm, I am getting this error: Object of type 'Voting' is not JSON serializable

            – user2896120
            Nov 21 '18 at 3:57











          • Add a serializer for it then.

            – Red Cricket
            Nov 21 '18 at 4:05











          • How would you do it in this situation? I am not too familiar with functions inside serializers

            – user2896120
            Nov 21 '18 at 4:11











          • I would add a serializer class like you have for ChoiceSerializer but the class name would be VotingSerializer and it would have Model = Voting

            – Red Cricket
            Nov 21 '18 at 5:52













          • Hmm, I did that but I am getting the same error. I added what I did in my question please take a look at the edits see if I'm doing it correctly?

            – user2896120
            Nov 21 '18 at 5:59

















          Hmm, I am getting this error: Object of type 'Voting' is not JSON serializable

          – user2896120
          Nov 21 '18 at 3:57





          Hmm, I am getting this error: Object of type 'Voting' is not JSON serializable

          – user2896120
          Nov 21 '18 at 3:57













          Add a serializer for it then.

          – Red Cricket
          Nov 21 '18 at 4:05





          Add a serializer for it then.

          – Red Cricket
          Nov 21 '18 at 4:05













          How would you do it in this situation? I am not too familiar with functions inside serializers

          – user2896120
          Nov 21 '18 at 4:11





          How would you do it in this situation? I am not too familiar with functions inside serializers

          – user2896120
          Nov 21 '18 at 4:11













          I would add a serializer class like you have for ChoiceSerializer but the class name would be VotingSerializer and it would have Model = Voting

          – Red Cricket
          Nov 21 '18 at 5:52







          I would add a serializer class like you have for ChoiceSerializer but the class name would be VotingSerializer and it would have Model = Voting

          – Red Cricket
          Nov 21 '18 at 5:52















          Hmm, I did that but I am getting the same error. I added what I did in my question please take a look at the edits see if I'm doing it correctly?

          – user2896120
          Nov 21 '18 at 5:59





          Hmm, I did that but I am getting the same error. I added what I did in my question please take a look at the edits see if I'm doing it correctly?

          – user2896120
          Nov 21 '18 at 5:59




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403329%2fcreating-serializer-to-display-correct-data%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)