質問に答えるのは簡単に思え、答えはどこかの API ref にあることは知っていますが、私は django に少し慣れていないので、これを成し遂げるために何日も API を使ってきました。どんな助けでも大歓迎です!
大学のコンピュータ ラボ用に基本的なブログ アプリを作成しています。このアプリには、関連する 2 つのページがあります。キャンパス内の各ラボに関する情報 (時間、場所/建物) を表示する場所ページと、各ラボの機器に関する情報を表示するリソース ページ。
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>
このように表示するポイントは、大学が Web ページ上の情報の表示方法について厳格なガイドラインを持っており、すべてをきれいに整理された表にまとめたいということです。django admin を使用してコンピューター/プリンターの種類を追加または削除するユーザーをサポートするには、テーブルの最初の列に動的な行スパンが必要です。
StackOverflow を検索したところ、私のものと同様の問題がいくつか見つかりました。彼らは prefetch_related を使用して 1 つのバッチ クエリで関連オブジェクトを取得すると言っていましたが、これを行ったときに TypeError "RelatedManager" is not an iterable を取得し始めました。テンプレート内のプリンター。なぜこれが起こっているのか理解しています。これは、クエリを処理する RelatedManager クラスがリスト/配列/タプルを返さないためです。必要な方法で必要な情報にアクセスする方法がまったくわかりません。
コメントアウトされた Generic View で部分的に動作していましたが、使用すると
location.lab_printers.count
、値に一貫性がなくなり、データベース内の実際のオブジェクトが反映されず、書式設定が台無しになり、td 要素が失われ、表示が不正確になりました。
とりとめなく申し訳ありませんが、これは単なる複雑な問題であり、これをどのように行うべきかについてのアイデアがまったくありません。
ありとあらゆる助けをいただければ幸いです。お時間をいただきありがとうございます!