EviSvil
EviSvil

Reputation: 636

Django Filter taking list of foreign key model

I have this two model Route and Project and a relation models:

class ProjectRoute(models.Model):
    #Fk
    project                     = models.ForeignKey(Project, null = False, on_delete = CASCADE)
    route                       = models.ForeignKey(Route, null = False, on_delete = CASCADE)

Having project ID I want to retrieve a list of routes.

relations = ProjectRoute.objects.filter(project__id = project_id)

With this filter, I have a list of ProjectRoute. What I whant is the queryset of only route. Something like this (that doesn't work):

routes = ProjectRoute.objects.filter(project__id = project_id).value_list(route)

Is it possible?

EDIT:

This is the code now. I want to remove FOR:

routes_relations           = ProjectRoute.objects.filter(project__id = project_id)
routes = []
for rr in routes_relations:
    routes.append(rr.route)
return routes

Upvotes: 0

Views: 51

Answers (1)

JPG
JPG

Reputation: 88509

to retrieve all Route s associated with a project_id id, use the below query

Route.objects.filter(projectroute__project_id=project_id).distinct()

Upvotes: 1

Related Questions