Advertisement
Larrisa

Polls list update views

Apr 20th, 2020
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. class Choice(models.Model):
  2.     question = models.ForeignKey(Poll, on_delete=models.CASCADE)
  3.     choice_text = models.CharField(max_length=200)
  4.     votes = models.IntegerField(default=0)
  5.  
  6.     def __str__(self):
  7.         return self.choice_text
  8.  
  9. class Poll(models.Model):
  10.     question = models.CharField(max_length=200)
  11.     pub_date = models.DateTimeField(auto_now=True)
  12.     created_by = models.ForeignKey(User, on_delete=models.CASCADE)
  13.  
  14.     def __str__(self):
  15.         """
  16.        Models string represantation
  17.        """
  18.         return self.question
  19.  
  20. ##Serializers
  21.  
  22. class ChoiceSerializer(serializers.ModelSerializer):
  23.     """Serialize all model fields for Choice model"""
  24.     votes = VoteSerializer(many=True, read_only=True, required=False)
  25.  
  26.     class Meta:
  27.         model = Choice
  28.         fields = '__all__'
  29.  
  30. ##Views
  31. class ChoiceCustomView(generics.ListCreateAPIView):
  32.     """View to fetch choices given a certain poll"""
  33.  
  34.     def get_queryset(self):
  35.         queryset = Choice.objects.filter(question_id=self.kwargs['pk'])
  36.  
  37.         return queryset
  38.  
  39.     serializer_class = ChoiceSerializer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement