我如何在模板中使用反向关系项django

发布于 2025-02-13 02:11:09 字数 1117 浏览 0 评论 0原文

 {% for order in orders %}
  <li>{{order.customer.last_name}} - {{ order.orderitem_set.product.unit_price }}</li>
  {% endfor %}

class Product(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    unit_price = models.DecimalField(max_digits=6, 
    decimal_places=2)
    inventory = models.IntegerField()
    last_update = models.DateTimeField(auto_now=True)
    collection = models.ForeignKey(Collection, 
    on_delete=models.PROTECT)
    promotions = models.ManyToManyField(Promotion)

class Order(models.Model):
    placed_at = models.DateTimeField(auto_now_add=True)
    customer = models.ForeignKey(Customer, 
    on_delete=models.PROTECT)

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.PROTECT)
    product = models.ForeignKey(Product, on_delete=models.PROTECT)
    quantity = models.PositiveSmallIntegerField()
    unit_price = models.DecimalField(max_digits=6, 
    decimal_places=2)

我如何在浏览器中获得unit_price,last_name显示,但是当我尝试使用django反向关系创建的项目时,值不显示值

 {% for order in orders %}
  <li>{{order.customer.last_name}} - {{ order.orderitem_set.product.unit_price }}</li>
  {% endfor %}

class Product(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    unit_price = models.DecimalField(max_digits=6, 
    decimal_places=2)
    inventory = models.IntegerField()
    last_update = models.DateTimeField(auto_now=True)
    collection = models.ForeignKey(Collection, 
    on_delete=models.PROTECT)
    promotions = models.ManyToManyField(Promotion)

class Order(models.Model):
    placed_at = models.DateTimeField(auto_now_add=True)
    customer = models.ForeignKey(Customer, 
    on_delete=models.PROTECT)

class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.PROTECT)
    product = models.ForeignKey(Product, on_delete=models.PROTECT)
    quantity = models.PositiveSmallIntegerField()
    unit_price = models.DecimalField(max_digits=6, 
    decimal_places=2)

How can I get products unit_price in browser, last_name shows but when I am trying to use django reverse relation created item the value don't showing

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请别遗忘我 2025-02-20 02:11:09

订单可以由多个项目组成,您必须在集合上迭代(反向关系):

{% for item in order.orderitem_set.all %}
    {{ item.product.title }}
{% endfor %}

habe a the 查询反向关系

As an order can consist of multiple items you would have to iterate over the set (the reverse relation):

{% for item in order.orderitem_set.all %}
    {{ item.product.title }}
{% endfor %}

Habe a look at the documentation for querying reverse relations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文