Django - Get Foreign key objects in single query?
Asked Answered
E

2

27

I'm finding django foreign keys a bit confusing, is there any way to do the view below, using a single query?

# Model
class Programme(models.Model):
    name = models.CharField(max_length = 64)

class Actor(models.Model):
    programme = models.ForeignKey(Programme)
    name = models.CharField(max_length = 64)


# View
def list_actors( request, programme_id):
    programme = Programme.objects.filter(id = programme_id)[0]
    actors = Actor.objects.filter(programme = programme_id)
    json = simplejson.dumps( [{
        'name': str(actor.name),
        'rating': str(actor.rating),} for actor in actors] )
    return HttpResponse(json, mimetype='application/javascript')
Englebert answered 2/3, 2010 at 23:34 Comment(0)
R
14

You query Programme and assign to programme, but you never use the result anywhere. Just remove that line.

Regulus answered 2/3, 2010 at 23:42 Comment(0)
F
32

I think you are looking for select_related().

This line:

actors = Actor.objects.filter(programme = programme_id)

should look like this:

actors = Actor.objects.select_related().filter(programme = programme_id)

Unfortunately as emphasized here: Get foreign key objects in a single query you will only be able to retrieve actors that way as select_related only works on objects having ForeignKeys and not vice versa.

Fanatical answered 24/7, 2012 at 10:30 Comment(1)
select_related would only be needed if you wanted to access actor.programme.name without an extra DB hit per actor. Otherwise it's superfluous.Pomposity
R
14

You query Programme and assign to programme, but you never use the result anywhere. Just remove that line.

Regulus answered 2/3, 2010 at 23:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.