假設您正在製作一個網站來簡單列出您的產品。Django:處理模板頁面中的外鍵請求的最佳方式
您想要爲您的每個產品上傳未指定數量的圖片。所以,你,下面的Django的多到一個文檔,使兩種型號:
# 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)
現在,如果我想所有的發言權產品1的圖片,我可以使用來獲取它們:
ProductImages.objects.filter(product__pk=1)
我問題從這裏開始。
假設您想要一個索引頁面,其中只顯示了所有產品的清單,並且爲了簡單起見,這是與每個產品關聯的第一個圖像。
你讓一個模板頁面
{% for product in product list %}
<div class="product-listing" style="display:inline">
<!-- image for product goes here -->
<!-- brief description goes here -->
</div>
{% endfor %}
其中product_list
在您的環境傳送:
# inside /my_app/views.py
def index(request):
...
context = {"product_list": Product.objects.all()}
...
問題:什麼是也有機會獲得用於顯示圖像的最佳方式模板頁面中的圖像?
目前我認爲構建並行圖像列表就足夠了:
# 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循環計數器來獲得該產品的相應的圖像。
例如
{% 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