Reputation: 3506
I have two models: Site
and Metric
.
I want to display the Metric
values alongside each Site
.
My views.py
is as follows:
from django.shortcuts import render
from .models import Site, Metric
def site_graph(request):
sites = Site.objects.order_by('name')
metrics = [s.metric_set.all() for s in sites]
return render(request, 'da/site_graph.html', {'sites': sites, 'metrics': metrics})
And my template content looks like this:
{% block content %}
{% for metric in metrics %}
[
{% for query in metric %}
{{ query.domain_authority }}
{{ query.date_queried }}
{% endfor %}
]
{% endfor %}
{% endblock content %}
I am not sure how I would go about getting the data I need in Django.
This data is going to be eventually passed onto d3.js
for visualization which is why I need the data from the matching the primary key for each Site
to be together.
Upvotes: 1
Views: 48
Reputation: 3308
You can use a list of dictionaries:
def site_graph(request):
metrics=[]
sites = Site.objects.order_by('name')
for site in sites:
metrics_site={}
metrics_site["site"] = site
metrics_site["metrics"] = site.metric_set.all()
metrics.append(metrics_site)
return render(request, 'da/site_graph.html', {'metrics': metrics})
And then in the template:
{% block content %}
{% for metric in metrics %}
{{ metric.site.name }}
{% for query in metric.metrics %}
{{ query.domain_authority }}
{{ query.date_queried }}
{% endfor %}
{% endfor %}
{% endblock content %}
metric.site.name is just an example if your model "site" contains a field "name" that you want to show.
Upvotes: 1