在serializers.IntegerField(validators = ...)中解析多个参数值

问题描述 投票:1回答:2

我正在使用djangomysql

serializers.py我有:

class UserWorseQuestListSerializer(serializers.Serializer):
    user_id = serializers.CharField(max_length=255, validators=[user_exists])
    section_id = serializers.IntegerField(validators=[section_exists_in_completed_quest])

而我的section_exists_in_completed_quest包含:

def section_exists_in_completed_quest(section_id):
    if section_id is None:
        raise serializers.ValidationError('section_id must be specified')
    quest_ids = CompletedQuestion.objects.filter(question__section_id = section_id) \
    .values_list("question_id", flat=True).distinct()
    #print (quest_ids)
    if not quest_ids:
        msg = 'Completed questions in Section {} were not found for user {}'
        raise serializers.ValidationError(msg.format(section_id))

我的问题是我是否能够在user_id中传递section_exists_in_completed_quest()的值。

如果我像def section_exists_in_completed_quest(section_id, user_id):一样传递它我得到HTTP/1.1" 500 27错误。

你能帮我吗?

mysql django serialization
2个回答
0
投票

既然知道我找不到解决方案,这就是我建议使用SessionStore()

from django.contrib.sessions.backends.db import SessionStore

s = SessionStore()

def user_exists(user_id):
    if user_id is None:
        raise serializers.ValidationError('user_id must be specified')
    if not User.objects.filter(id=user_id).exists():
        msg = 'User {} not found'
        raise serializers.ValidationError(msg.format(user_id))
    s['user_id']= user_id

def section_exists_in_completed_quest(section_id):
    if section_id is None:
        raise serializers.ValidationError('section_id must be specified')
    quest_ids = CompletedQuestion.objects.filter(user_id__exact=s['user_id'] ,question__section_id = section_id) \
    .values_list("question_id", flat=True).distinct()

0
投票

您可以编写一个可以访问多个字段的validate方法,而不是使用验证器。

class UserWorseQuestListSerializer(serializers.Serializer):
    user_id = serializers.CharField(max_length=255, validators=[user_exists])
    section_id = serializers.IntegerField()

    def validate(self):
        section_id = data['section_id']
        user_id = data['user_id']
        ...

有关更多信息,请参阅object level validation上的文档。

© www.soinside.com 2019 - 2024. All rights reserved.