Stuart Axon
Stuart Axon

Reputation: 1874

Django - Get Foreign key objects in single query?

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')

Upvotes: 27

Views: 101701

Answers (2)

Alexey Vassiliev
Alexey Vassiliev

Reputation: 2435

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.

Upvotes: 32

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

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

Upvotes: 14

Related Questions