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() “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.
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.
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")
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.
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.
You query Programme
and assign to programme
, but you never use the result anywhere. Just remove that line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With