我将django
与mysql
一起使用。
在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
错误。
你能帮我吗?
答案 0 :(得分: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()
答案 1 :(得分: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上的文档。