あなたの製品を単純にリストアップするサイトを作っているとします。Django:テンプレートページで外部キーリクエストを処理する最善の方法
あなたの商品ごとに不特定多数の写真をアップロードしたいと考えています。
ProductImages.objects.filter(product__pk=1)
私:私が言うの製品1のための画像のすべてをしたい場合は
# files stored under my_app/static/my_app/product_images/product_<id>/<img_name>
def product_img_dir_path(instance, filename):
return 'my_app/static/my_app/product_images/product_{0}/{1}'.format(instance.product.id, filename)
class Product(models.Model):
name = models.CharField ...
... # other attributes of the product, e.g. price, etc
class ProductImage(models.Model):
product = models.ForeignKey("Product", on_delete=models.CASCADE)
image = models.ImageField(upload_to=product_img_dir_path)
さて、私が使用してそれらを取得することができます。だから、Djangoの多対一のドキュメント以下、2つのモデルが作りますここから質問が始まります。
すべての商品のリストと、各商品に関連付けられている最初の画像を簡単に表示するためのインデックスページが必要な場合を考えます。
# inside /my_app/views.py
def index(request):
...
context = {"product_list": Product.objects.all()}
...
質問:何も表示するための画像へのアクセスを持っているための最良の方法です
あなたはproduct_list
があなたのコンテキストで可決された
{% for product in product list %}
<div class="product-listing" style="display:inline">
<!-- image for product goes here -->
<!-- brief description goes here -->
</div>
{% endfor %}
でテンプレートページを作りますテンプレートページ内の画像?製品に対応する画像を取得するためにforloopカウンタを使用して何とかその後、
# inside /my_app/views.py
def index(request):
...
product_list = Product.objects.all()
image_list = [product.productimage_set.all()[0] for product in product_list]
context = {"product_list": product_list, "image_list": image_list}
...
をして:
は現在、私は、並列画像リストを構築することは十分だろうと思いました。
{% for product in product list %}
<div class="product-listing" style="display:inline">
<img src="{{ image_list[<forloop counter>].image.url }}" />
<!-- brief description goes here -->
</div>
{% endfor %}
これを行うより良い方法はありますか?
どのように働くだろう、 '._set'サーバ側ではないでしょうか? – SumNeuron
テンプレートでもアクセスできます。私は私の答えに '.all'と書くのを忘れました、今は編集されています。これを参照してください:https://stackoverflow.com/questions/6217638/access-foreignkey-set-directly-in-template-in-django – wencakisa
これが動作します!しかし...それは私に404を提供する – SumNeuron