Django: 如何从两个模型中获取数据并在模板中显示?

有两个模型Product和ProductImage,我的代码如下。

models.py

class Product(models.Model):
   product_name = models.CharField(max_length=100)
   product_weight = models.CharField(max_length=30)

models.py

from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

_UNSAVED_IMAGEFIELD = 'unsaved_imagefield'

def upload_path_handler(instance, filename):
    import os.path
    fn, ext = os.path.splitext(filename)
    return "images/{id}/{fname}".format(id=instance.product_id, 
    fname=filename)

class ProductImage(models.Model):
   product = models.ForeignKey(Product, on_delete=models.DO_NOTHING)
   image = models.ImageField(upload_to=upload_path_handler, blank=True)

@receiver(pre_save, sender=ProductImage)
def skip_saving_file(sender, instance, **kwargs):
    if not instance.pk and not hasattr(instance, _UNSAVED_IMAGEFIELD):
        setattr(instance, _UNSAVED_IMAGEFIELD, instance.image)
        instance.image = None

@receiver(post_save, sender=ProductImage)
def update_file_url(sender, instance, created, **kwargs):
    if created and hasattr(instance, _UNSAVED_IMAGEFIELD):
        instance.image = getattr(instance, _UNSAVED_IMAGEFIELD)
        instance.save()

views.py

def products(request):
    products = Product.objects.all()
    context = {
        'products' : products
    }

    return render(request, 'products/products.html', context)

产品.html

{% if products %}
        {% for product in produucts %}
            <div class="col-sm-5 col-lg-5">
                <div class="equipmentbox">
                    <div class="equipmentimgbox"> <img src="{{"**IMAGE URL HERE**"}}"> </div>
                    <a href="">{{ product.product_name }}</a>
                </div>
            </div>
        {% endfor %}
    {% else %}
        <div class="col-md-12">
            <p>No Products Available</p>
        </div>
{% endif %}

Product table包含产品的详细信息,ProductImage包含与特定产品相关的图片。我有一个列表页,我想显示ProductTitle和Image。我如何从其他表中获取图片,并将其与产品标题一起显示。

先谢谢你。

解决方案:

这里是解决方案。

{% if products %}
        {% for product in produucts %}
            <div class="col-sm-5 col-lg-5">
                <div class="equipmentbox">
                    <div class="equipmentimgbox"> <img src="{{"product.productimage_set.all.0.image_main.url"}}"> </div>
                    <a href="">{{ product.product_name }}</a>
                </div>
            </div>
        {% endfor %}
    {% else %}
        <div class="col-md-12">
            <p>No Products Available</p>
        </div>
{% endif %}

查看这个问题了解更多细节。Django: 如何通过Template获取ForeignKey连接的数据?

给TA打赏
共{{data.count}}人
人已打赏
未分类

命令 "npx create-react-app project "不生成项目。

2022-9-12 9:54:20

未分类

libarchive 如何读取连接后的焦油。

2022-9-12 9:54:22

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索