How to convert this raw query to query set?

I’m new to django, and i want to show field that related to foreign key in another table. this is the table.


i want to career table got the career_tag_name and hex_code from table color. i’ve tried the Career.objects.raw() this is the query in

careers = Career.objects.raw('''SELECT website_career_tag.career_tag_name,website_color.hex_code, website_career.* 
from website_career INNER JOIN website_career_tag on = website_career.career_tag_id_id 
LEFT JOIN website_color on  website_career_tag.color_id_id = website_color.ID''')

it works perfectly, until i want to use filter() by career_tag_name. when i use query set it’s more easy than make it raw to filter.

how do i make those raw query to query set?

You say that you are new to Django. Have you worked your way through the official tutorial and done the exercises?

i do, i’ve read about select_related. throuh, to_field, etc. but i didn’t get what i want…

So the point with the ORM is that you don’t need to explicitly specify a “join”. You automatically have access to related objects through the ForeignKey field.

Assume you have Models Career and CareerTag. In Career you have a field named career_tag, which is a ForeignKey field to CareerTag.

Now, lets say that you have an instance of Career named career. If so, career.career_name would be the reference to the String object stored in that column. In the exact same manner, career.career_tag would be the reference to the instance of CareerTag to which that instance of Career refers. Continuing on with that, career.career_tag.color is your reference to the Color object, and so career.career_tag.color.color_name is the reference to that field in Color.

Side Note: Django creates the column for a ForeignKey field with an _id suffix, giving you access to either the referenced object or the pk field itself. This means you can access or reference either career.career_tag or career.career_tag_id - which are two different things.

Side note: Since you made the reference to select_related, I’ll mention here that that is a performance-enhancement available when you know you’re going to be using related objects in your view. It does not alter how you work with these queried objects.