我正在使用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
错误。
你能帮我吗?
既然知道我找不到解决方案,这就是我建议使用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()
您可以编写一个可以访问多个字段的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上的文档。