Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKiko Augusto
2,764 PointsCourse_fields description
I would like to know how I would describe a Foreign Key in the fields description if I wanted to serialise it as well.
Example:
Suppose that the Course model had a foreign key to an author:
class Course(Model): author = ForeignKey(Author, related_name="course_author")
How I should describe it in the course_fields dictionary?
Many thanks.
1 Answer
David Lin
35,864 PointsAssuming the Author field you want to return is "name," then perhaps something like:
course_fields = {
'id': fields.Integer,
'title': fields.String,
'url': fields.String,
'reviews': fields.List(fields.String),
'author_name': fields.String
}
def add_author(course):
course.author_name = course.author.name
return course
That is, since author is a field of your course model, then it is accessible as course.author
. Then, just access the field of the author (presumably defined in your Author model class) that you want to return in the response, for example, course.author.name
class Author(Model):
name = CharField()
Note: You wouldn't want to specify the "author" field directly in course_fields
, because if you do, the reference to the Author object will be returned (something like <models.Author object at 0x110097a20>), which is probably not what you want. That's why I specified a related name "author_name" instead, and used a helper method to assign the string course.author.name
to it instead.