【问题标题】:Django serialize - adding another parameter to the serialized outputDjango 序列化 - 向序列化输出添加另一个参数
【发布时间】: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


【解决方案1】:

一个理智的简单解决方案是像这样覆盖 get_serialiser_class 方法:

def get_serializer_class(self):
    if self.get_object().activeCourse:
        return ActiveProfileSerializer
    else:
        return ProfileSerializer

ActiveProfileSerializer 仅包含为具有活动课程的学生提供的字段或您想提供的任何额外字段。这些字段应该在序列化器中定义为nested 关系:

那么在你的观点上你只需要调用:

serialiser = self.get_serializer_class()

获取正确的序列化数据。

这种方法的好处在于,它可以为您的视图返回正确的序列化程序类,从而更加解耦。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2021-09-17
    • 2017-11-11
    • 1970-01-01
    • 2021-08-12
    • 2017-10-03
    相关资源
    最近更新 更多