我知道这个问题似乎很容易回答,而且答案会在某个地方的 API 引用中,但我对 django 有点陌生,并且已经通过 API 倾注了好几天试图完成这项工作。任何帮助将不胜感激!
我正在为我大学的计算机实验室创建一个基本的博客应用程序,在这个应用程序中你有两个相关的页面。位置页面显示有关校园内每个实验室的信息(小时、位置/建筑物),以及显示有关每个实验室设备信息的资源页面。
我的 models.py 文件如图所示设置(还有其他模型,但这些是唯一相关的:
class Location(models.Model):
name = models.CharField(max_length=100)
computer = models.ForeignKey('Computer')
printer = models.ForeignKey('Printer')
class Computer(models.Model):
computer_location = models.ForeignKey('Location', related_name='lab_computers')
computer_model = models.ForeignKey('HardwareModel')
class Printer(models.Model):
printer_location = models.ForeignKey('Location', related_name='lab_printers')
printer_model = models.ForeignKey('HardwareModel')
class HardwareModel(models.Model):
brand = models.CharField(max_length = 100)
model_num = models.CharField(max_length = 30)
我的views.py 文件:
class LocationsView(generic.ListView): #This isn't the view to be concerned with
template_name = 'blog/location_list.html'
context_object_name = 'locations'
queryset = Location.objects.all()
#This is commented out because i was trying to modify the view to allow extra context
#I'm aware that you can't have 2 views with the same name. Just assume only one is active
#class ResourcesView(generic.ListView):
# context_object_name = 'locations'
# queryset = Location.objects.all()
def ResourcesView(request):
locations = Location.objects.prefetch_related('lab_printers').all()
return render_to_response('blog/resource_list.html',
{'locations': locations})
我需要在其中显示的模板是这样的:
<table>
<tr>
<th>Lab</th>
<th>Device</th>
<th>Type</th>
<th>Model</th>
</tr>
{% for location in locations %}
<tr>
<td rowspan="{{ location.lab_printers.count }}">{{ location.name }}</td>
<td>Computer</td>
<td>{{ location.computer.computer_model.brand }}</td>
<td>{{ location.computer.computer_model.model_num }}</td>
</tr>
<tr>
<td>Printer</td>
<td>{{ location.printer.printer_model.brand }}</td>
<td>{{ location.printer.printer_model.model_num }}</td>
</tr>
{% endfor %}
</table>
像这样显示它的重点是大学对如何呈现网页上的信息有严格的指导方针,他们希望一切都在整齐有序的表格中。该表需要在第一列上具有动态行跨度,以支持人们通过 django admin 添加或删除计算机/打印机类型。
我通过 StackOverflow 进行搜索,发现了一些与我类似的问题,他们说使用 prefetch_related 来在一个批处理查询中获取相关对象,但是当我这样做时,我开始得到一个 TypeError "RelatedManager" is not an iterable 在尝试访问时模板中的打印机。我明白为什么会这样。这是因为处理查询的相关管理器类不返回列表/数组/元组。我只是不知道如何以我需要的方式访问我需要的信息。
我确实让它部分使用了注释掉的通用视图,但是当我使用时
location.lab_printers.count
返回的值不一致并且没有反映数据库中的实际对象,弄乱了格式,并导致缺少 td 元素和不准确的显示。
抱歉,如果我漫无边际,这只是一个复杂的问题,我完全没有关于如何去做这件事的想法。
非常感谢任何和所有帮助。感谢您的时间!