我有以下模型,并希望在Web API中显示一些必需的结果。
class Poll(models.Model):
question = models.CharField(max_length=100)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
pub_date = models.DateTimeField(auto_now=True)
class Choice(models.Model):
poll = models.ForeignKey(Poll, related_name='choices', on_delete=models.CASCADE)
choice_text = models.CharField(max_length=100)
class Vote(models.Model):
choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE)
poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
voted_by = models.ForeignKey(User, on_delete=models.CASCADE)
我以如下方式进行设置:
class VoteSerializer(serializers.ModelSerializer):
voted_by = serializers.StringRelatedField(many=False)
class Meta:
model = Vote
fields = '__all__'
class ChoiceSerializer(serializers.ModelSerializer):
votes = VoteSerializer(many=True, required=False)
class Meta:
model = Choice
fields = '__all__'
class PollSerializer(serializers.ModelSerializer):
choices = ChoiceSerializer(many=True, read_only=True, required=False)
created_by = serializers.StringRelatedField(many=False)
class Meta:
model = Poll
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User(
email=validated_data['email'],
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
Token.objects.create(user=user)
return user
我想要一个结果,其中只有那些投票显示在vote_by =“选择ID”的选项中。 **但结果包括所有投票**
{ “ id”:1 “投票”:[ { “ id”:1 “ voted_by”:1 “选择”:1, “民意调查”:1 }, { “ id”:2 “ voted_by”:2 “选择”:1, “民意调查”:1 } ], “ choice_text”:“它提供Web API和身份验证权限以确保安全。”, “民意调查”:1 }