Django:如何从两个模型中获取数据并将其显示在模板中?
Posted
技术标签:
【中文标题】Django:如何从两个模型中获取数据并将其显示在模板中?【英文标题】:Django: How to fetch data from two models and display it i template? 【发布时间】:2020-08-09 06:51:38 【问题描述】:有两个模型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)
products.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 表包含产品详细信息,ProductImage 包含与特定产品相关的图像。我有一个列表页面,我想在其中显示 ProductTitle 和 Image。如何从另一个表中获取图像并将其与产品标题一起显示。
提前致谢。
【问题讨论】:
你在哪里定义ProductImage
?
我不确定在哪里以及如何定义它
我找到了使用这个***.com/questions/11056844/…的解决方案
【参考方案1】:
解决办法如下:
% 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: How to get data connected by ForeignKey via Template?
【讨论】:
以上是关于Django:如何从两个模型中获取数据并将其显示在模板中?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 GeoIP2() django 模型从 IP 地址调用中提取保存的信息以显示在我的 html 中