django values_list() 和图片反向外键

django values_list() and image reverse foreign key

我的图片有问题,它们没有显示在模板中,谁能帮我解决一下

class Product(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    myshop = models.ForeignKey(MyShop, on_delete=models.CASCADE, related_name="shop_product")
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)

class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_image")
    image = models.ImageField(upload_to='products/images',
                          validators=[validate_image_file_extension, validate_file_size,
                                      FileExtensionValidator(['JPEG', 'JPG', 'PNG'])])

{% for product in products %}  
    {% for image in product.product_image.all %}
        {% if image.is_feature %}
            <img src="{{ image.image.url }}" alt="" width="80" height="80">
        {% endif %}
    {% endfor %}
{% endfor %}



products = Product.prod_obj.select_related(
        'myshop'
    ).filter(id__in=product_ids).values_list('myshop', 'title', 'description', 'product_image', named=True)

不要使用.values_list() [Django-doc] or .values() [Django-doc]:它删除了模型逻辑层,因此,您确实无法再访问.url

查询方式:

products = Product.prod_obj.select_related('myshop').<strong>prefetch_related(</strong>
    'product_image'
<strong>)</strong>.filter(id__in=product_ids)

有关详细信息,请参阅我写的article on (over)use of .values()