Django - Get foreign key objects in a single request?

I find django's foreign keys a bit confusing, is there a way to make the view below using a single request?

# 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') 
+7
python django foreign-key-relationship
source share
2 answers

You request a Programme and assign a Programme , but never use the result anywhere. Just delete this line.

+9
source share

I think you are looking at something like this:

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

which were selected, attached, you put before the final receipt. This is your line:

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

should look like

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

Unfortunately, as indicated here: to get foreign key objects in one request - Django , you can only retrieve actors in the same way as select_related only works on objects that have ForeignKeys and not vice versa.

+9
source share

All Articles