2016-07-13 48 views
3

我正在嘗試迭代模型以獲取列表中的第一個圖像,並且它給了我模型不可迭代的錯誤。以下是我的代碼模型和模板。我只需要獲取與單一產品相關的列表中的第一張圖片。Django模型在模板中不可迭代

models.py:

class Product(models.Model): 
    title = models.CharField(max_length=500) 
    description = models.TextField(blank=True, null=True) 
    price = models.DecimalField(max_digits=20, decimal_places=2) 
    sku = models.CharField(null=True, max_length=100) 
    url = models.URLField(blank=True) 
    slug = models.SlugField(unique=True) 
    categories = models.ManyToManyField('Category', blank=True) 
    default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True) 
    provider = models.ForeignKey('Product', on_delete=models.CASCADE) 

    def __unicode__(self): 
     return self.title 

    def get_absolute_url(self): 
     return reverse('product_detail', kwargs={"slug": self.slug}) 

    def get_image_url(self): 
     img = self.productimage_set.first() 
     if img: 
      return img.image.url 
     return img 
    def get_image_list(self): 
     return self.productimage_set.all() 

def image_upload_to(instance, filename): 
    title = instance.product.title 
    slug = slugify(title) 
    basename, file_extension = filename.rsplit('.', 1) 
    new_filename = '%s-%s.%s' % (basename, instance.id, file_extension) 
    return 'products/%s/%s' % (slug, new_filename) 

class ProductImage(models.Model): 
    product = models.ForeignKey(Product) 
    image = models.ImageField(upload_to=image_upload_to) 

    def __unicode__(self): 
     return self.product.title 

prduct_detail.html:

<div class="pics clearfix"> 
<div class="thumbs"> 
{% for img in product.get_image_list %} 
<div class="preview"> 
<a href="{{ img.get_absolute_url }}" class="selected" data-full="{{ img.image.url }}" data-title="title"> <img src="{{ img.image.url }}"> </a> 
</div> 
{% endfor %} 
</div> 
<div class="imglarge"> 
{% for img in object.productimage_set.all %} 

<a href="{{ object.get_absolute_url }}" class="full" title="title"> <img src="{{ img.image.url }}"> </a> 

{% endfor %} 

</div> 
</div> 

圖像列表來了罰款,但第一圖像不來了因爲它要麼顯示了{% for img in object.productimage_set.first %}所有的圖像就顯示錯誤如下:

'ProductImage' object is not iterable 
Request Method: GET 
Request URL: http://localhost:8000/items-for-kids 
Django Version: 1.8.13 
Exception Type: TypeError 
Exception Value:  
'ProductImage' object is not iterable 
Exception Location: C:\Users\AliKhan\eCom\lib\site-packages\django\template\defaulttags.py in render, line 161 
Python Executable: C:\Users\AliKhan\eCom\Scripts\python.EXE 
Python Version: 2.7.9 

回答

2

你可以用它代替forwith標籤,以避免錯誤:

更改此:

{% for img in object.productimage_set.first %} 
... 
{% endfor %} 

{% with img=object.productimage_set.first %} 
... 
{% endwith %} 
+1

它爲我工作。謝謝 –

3

您使用all得到個所有的相關產品圖像和遍歷他們:

{% for img in object.productimage_set.all %} 

但是,如果你得到一個單一的對象,當你得到的第一個相關產品的形象一樣,那麼你不能重複:

{{ object.productimage_set.first }} 

這就是爲什麼你得到錯誤的原因

object is not iterable

你只有一個對象。如果您需要所有對象,則應考慮使用all