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')
select_related
would only be needed if you wanted to accessactor.programme.name
without an extra DB hit per actor. Otherwise it's superfluous. – Pomposity