[Fixed]-Django ORM SELECT with join


The following selects the values related to particular record id. You can then follow the foreign keys to get the related record and key. Using select_related minimises database lookups.

# Select all values related to a record in your view
record = Record.objects.get(pk=record_id)
values = Value.objects.filter(record=record).select_related()

# In your template
{% for value in values %}
{{ value.record.name }} - {{ value.key.name }} - {{ value.value }}
{% endfor %}

Selecting more that one record

In your sql, you had WHERE record_id = 1, so I showed how to get all the values for a particular record. You could also select the values for more that one record in one query.

# filter all records which belong to the project with `project_id=1`
records = Record.objects.filter(project_id=1)
# select all values that belong to these records
values = Value.objects.filter(record__in=records).select_related().order_by('record')


Should be relatively straightforward, since you already have the foreign keys tied together.

Record.objects.select_related().filter(id = variable_that_stores_id)

You can combine that with only to limit the fields that you want to bring back.


Leave a comment