I have a django model with two classes Students and Courses. In a get request method I wish to extract the student information and the course s/he is taking (they can take only one course). Since a student can be registered and not have an active course, my return result should either include only the student data or the student data as well as the name of the course s/he is taking.
the naive version for this kind of code will be:
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")
Question 1: if the Courses table has also a field called name and not courseName when calling serialize how to distinguish between student.name and studentCourse.name?
Question 2: Can it be done without redundant code? that means my code will look something like this:
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")
Classes..objects#here I'd like to add to output the field classNameoutputvariable is the one you set inside theifstatement; if it isn't, you know it was set in theelsestatement.