Django - Get Foreign key objects in single query?


Question

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')
1
13
3/29/2013 10:05:27 AM

Accepted Answer

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

9
3/2/2010 11:42:21 PM

I think you are looking to something like that:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related

which are select_related, you put before final get. That is your line:

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

should look like

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon