【发布时间】:2015-05-03 19:24:09
【问题描述】:
我有一个 django 模型,有两个班级学生和课程。在获取请求方法中,我希望提取学生信息和他/她正在学习的课程(他们只能学习一门课程)。由于学生可以注册但没有有效课程,因此我的返回结果应仅包含学生数据或学生数据以及她/他正在学习的课程名称。
这种代码的原始版本是:
student = Students.objects.filter(id=student_id)
if student[0].activeCourse:
studentCourse = UniversityCourses.objects.filter(id=student[0].activeCourse)
combined_data = list(chain(student, studentCourse))
output = serializers.serialize('json', combined_data, fields=('name', 'age' 'id', 'courseName'))
else:
output = serializers.serialize('json', user, fields=('name', 'age' 'id'))
return HttpResponse(output, content_type="application/json")
问题一:如果 Courses 表还有一个字段名为 name 而不是 courseName 在调用 serialize 时如何区分 student.name 和 studentCourse.name?
问题2:可以不用冗余代码吗?这意味着我的代码将如下所示:
student = Students.objects.filter(id=student_id)
output = serializers.serialize('json', user, fields=('name', 'age' 'id'))
if student[0].activeClass:
#add the courseName to the already defined output
return HttpResponse(output, content_type="application/json")
【问题讨论】:
-
不知道是不是只有我一个人没看懂问题?
-
好的,15 分钟后,我仍然不知道你的问题是什么。 (你的句子中有太多歧义)。 “你的输出看起来像:......???” “将该类信息添加到输出中???”什么……我不明白……
Classes..objects#here I'd like to add to output the field className -
@RafaelCardoso 你能告诉我在哪里澄清吗,我不是说英语的人
-
@Yeo 如果现在问题和我的问题更清楚了,请告诉我。
-
您可以通过检查“courseName”是否在您传递的数据中来区分这两个输出。如果是,那么您知道
output变量是您在if语句中设置的变量;如果不是,您知道它是在else语句中设置的。
标签: python django concatenation