I do not understand how to get my queryset from the ManyToManyField in my ListView
Models
class Monolithic(models.Model):
obj = models.CharField( max_length=128, blank=False, null=False, unique=True)
face2 = models.ManyToManyField(FacePng)
class FacePng(models.Model):
obj = models.CharField( max_length=128, blank=False, null=False, unique=True)
png = models.CharField(max_length=128, blank=True, null=Tr
ue)
My details view works as expected.
View
class MonolithicDetailView(DetailView):
model = Monolithic
template_name = 'items/monolithic_detail.html'
def get_object(self):
id_ = self.kwargs.get("id")
return get_object_or_404(self.model, id=id_)
def get_context_data(self, *args, **kwargs):
context = super(MonolithicDetailView, self).get_context_data(**kwargs)
context['cdn_face'] = settings.CDN_URL
context['rvcs_url'] = settings.RVCS_URL
context['the_faces'] = self.get_object().face2.all()
return context
Template
<tr class="table-bordered">
<td>{{ object.name|title|default:"Missing" }}</td>
<td>{{ object.object }}</td>
<td><a href="{{ rvcs_url }}{{ object.arc_filename }}">{{ object.arc_filename }}</a></td>
<td>
{% for item_face in the_faces %}
<img src="{{ cdn_face }}{{ item_face.png }}" alt="{{ item_face.obj }}" class="img-thumbnail">
{% empty %}
No Face
{% endfor %}
</td>
<td>{{ object.ac }}</td>
<td>{{ object.weight }}</td>
<td>{{ object.value }}</td>
<td>
{% for mat in material %}
{{ mat }}
{% empty %}
None
{% endfor %}
</td>
</tr>
Screenshot (detail view)
How do a do something similar for the ListView?
View
class MonolithicListView(ListView):
model = Monolithic
template_name = 'items/monolithic_list.html'
paginate_by = 15
def get_queryset(self):
items = self.model.objects.all()
return items
def get_context_data(self, **kwargs):
context = super(MonolithicListView, self).get_context_data(**kwargs)
context['cdn_face'] = settings.CDN_URL
return context
Template
{% for item in object_list %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td><a href="{{ item.get_absolute_url }}">{{ item.name}}({{item.object}})</a></td>
<td><img src="{{ cdn_face }}{{ item.face2 }}" alt="{{ item.object }}" class="img-thumbnail"></td>
<td>{{ item.ac }}</td>
<td>{{ item.weight }}</td>
<td>{{ item.value }}</td>
<td>{{ item.material }}</td>
{% empty %}
<td>No armour found.</td>
</tr>
{% endfor %}
</tbody
>
I do not need to display all the faces, just one would be fine. What I do not know how to do is build a query for all objects in the Monolithic table with their associated graphics from the FacePng table.
I tried something like this:
def get_queryset(self):
items = self.model.objects.all()
for item in items:
face = self.model.objects.filter(face2__obj=item.object)
item.face = face.first()
return items
Super slow, ton of SQL queries, shows my ignorance.
Any help would be appreciate. Thanks.