Reputation: 725
model
class Member(models.Model):
id_unit = models.ForeignKey(Unit)
id_fleet = models.ForeignKey(Fleet)
def __str__(self):
return str(self.id_fleet)
views.py
def fleet_member_view(request):
cursor = connection.cursor()
cursor.execute("select fleet_member.id_fleet_id, array_to_string(array_agg(fleet_member.id_unit_id),',') as id_unit
from fleet_member, setup_unit
where fleet_member.id_unit_id = setup_unit.id group by fleet_member.id_fleet_id")
row = cursor.fetchone()
return render(request,'fleet_member_view.html',{'row': row}, context_instance= RequestContext(request))
i want to show data in my template
{% for post in row %}
<tr class="odd gradeX">
<td>{{ post.id_fleet }}</td>
<td>{{ post.id_unit }}</td>
</tr>
{% endfor %}
but data cannot show anything, i try query SQL in command line data show well. why data cannot show in template?
Upvotes: 1
Views: 765
Reputation: 21506
cursor.fetchone()
retrieves the next row of a query result set and returns a single sequence, or None
.
{% ifnotequal row None %}
<tr class="odd gradeX">
<td>{{ row.0 }}</td>
<td>{{ row.1 }}</td>
</tr>
{% endifnotequal %}
You want to list all results, you should use cursor.fetchall()
View
def fleet_member_view(request):
cursor = connection.cursor()
cursor.execute("select fleet_member.id_fleet_id, array_to_string(array_agg(fleet_member.id_unit_id),',') as id_unit
from fleet_member, setup_unit
where fleet_member.id_unit_id = setup_unit.id group by fleet_member.id_fleet_id")
row = cursor.fetchall()
return render(request,'fleet_member_view.html',{'row': row}, context_instance= RequestContext(request))
Template
{% for post in row %}
<tr class="odd gradeX">
<td>{{ post.0 }}</td>
<td>{{ post.1 }}</td>
</tr>
{% endfor %}
Upvotes: 3