2012-10-28 30 views
0

假設我有表ProductsImages,其中產品可以有多個圖像。在獲取搜索結果頁面的產品列表時,如何將第一個產品圖像包含爲縮略圖?Django - 加入相關表的第一行

當考慮到性能時,最好的方法是什麼? (查詢數量,內存,總時間等)

回答

0

我相信你會想直接在模板中獲取圖像。而不是在視圖中構建列表並將其傳遞到模板中,因爲會有多個項目。

所以我會推薦在Products模型中實現一個方法,該方法找到第一個圖像並返回它的url。

models.py

def Products(models.Model): 
    #your fields 

    def get_image_url(self): 
     try: 
      img = self.images_set.filter()[0] #get first image 
      return img.url() 
     except Exception: 
      return None 

模板:

{% for p in product_list %} 
    {# render product and add image #} 
    <img href="{{p.get_image_url }}" /> 
{% endfor %} 
+1

這會導致相對較大數量的查詢不成立? – RS7

0

如果您需要的性能提升W/O多架構改造,脫正常化是嘗試第一種方式:

class Product(models.Model): # instead of Products as convention 
    first_image = models.ImageField(editable=False, null=True) 

然後保持first_imageProduct.image_set得到更新時粗糙的信號。

此外,你甚至可以儲存一些傾倒場裏面的「weakref」(用這個當你真的需要它:)

class Product(models.Model): 
    # from django-jsonfield, store raw values of ImageField of the Images model 
    extra = JSONField() 
    def first_image(self): 
     image = self.extra.get('image') 
     return models.ImageField.attr_class(None, models.ImageField(), image) if image else None 

其它簡單的方法可以包括

  • 負載的第一印象批量處理,並按照Product()在模板循環中使用它們。第一張圖片需要標記以方便查詢。
  • 直接存儲first_imageProduct而不是Images。這對簡單的網站沒有太多的管理要求很好。