Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Get Foreign key objects in single query?

Tags:

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') 
like image 226
Stuart Axon Avatar asked Mar 02 '10 23:03

Stuart Axon


People also ask

What is the difference between Select_related and Prefetch_related?

select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship and does the “joining” in Python.

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

What is Related_name in Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set. Syntax: field_name = models.Field(related_name="name")

What is OneToOneField Django?

This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle. One-to-one relations are defined using OneToOneField field of django.


2 Answers

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.

like image 73
Alexey Vassiliev Avatar answered Oct 12 '22 06:10

Alexey Vassiliev


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

like image 45
Ignacio Vazquez-Abrams Avatar answered Oct 12 '22 06:10

Ignacio Vazquez-Abrams