25

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')
Lukasz Koziara
  • 4,274
  • 5
  • 32
  • 43
Stuart Axon
  • 1,844
  • 1
  • 26
  • 44

2 Answers2

31

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.

Alexey Vassiliev
  • 2,349
  • 2
  • 17
  • 8
  • 2
    `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. – Hamish Sep 28 '16 at 17:10
14

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358