【问题标题】:How to query objects from parent table along with data from related model如何从父表中查询对象以及相关模型中的数据
【发布时间】:2022-06-14 02:00:37
【问题描述】:

我有一个模型“产品”来上传产品。

class Product(BaseModel):
  ...
  ...
  class Meta:
    db_table = TABLE_PREFIX + "product"

我有另一个表,其中产品作为外键。

class ProductImage(BaseModel):
  product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)
  image = models.ImageField(upload_to='product')

  class Meta:
    db_table = TABLE_PREFIX + "product_image"

我想在主页显示这些产品。 我的主页视图为

def home(request):
  category_obj = Category.objects.all()
  product_obj = Product.objects.all().order_by('-id')
  
  context = {
        "title": "Home",
        "product_obj": product_obj,
        "category_obj": category_obj,
  }
  return render(request, "home/index.html", context)

我想在模板中显示产品和图像。

我可以在模板中显示除图像之外的所有细节。

<div class="dFlex product-list-wrap">
  {% for product in product_obj %}
    <div class="img-wrap">
      <img src="" alt="Product Image">
    </div>
    <h4>{{ product.name}}</h4>
    <p>{{ product.description}}</p>
  {% endfor %}
</div>

如何在我的模板上显示图像? 如何在查询产品的同时查询图片?

谢谢

【问题讨论】:

标签: django django-models django-views django-forms django-templates


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
相关资源
最近更新 更多