2017-08-16 27 views
0

假設您正在製作一個網站來簡單列出您的產品。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 %} 

有沒有更好的方法來做到這一點?

回答

1

只要您可以訪問product.productimage_set,就可以嘗試在模板中迭代它,並且不要將它作爲視圖上下文傳遞。

在你Django的模板

{% for product in product_list %} 
    <div class="product-listing" style="display:inline"> 
     {% for product_image in product.productimage_set.all %} 
      <img src="{{ product_image.image.url }}" /> 
      <!-- brief description goes here --> 
     {% endfor %} 
    </div> 
{% endfor %} 
+0

如何將這項工作,是不是'._set'服務器端? – SumNeuron

+0

您也可以在模板中訪問它。我忘了在我的答案中寫下'.all',現在編輯它。看到這個:https://stackoverflow.com/questions/6217638/access-foreignkey-set-directly-in-template-in-django – wencakisa

+0

這個工程!但是......它給了我404 – SumNeuron

0

我認爲,這將是您更輕鬆地解決這個問題,如果你通過將圖像移動到你的產品型號簡化設計。 如果你想保存圖像的路徑,它會更容易使用CharField,但如果你想保存許多路徑,爲什麼不使用JSONField?

我的建議是這樣的:

class Product(models.Model): 
    name = models.CharField(null=True, blank=True) 
    main_image = models.CharField(null=True, blank=True) # Optional 
    images = JSONField(null=True, blank=True) 
相關問題