如何从循环中的外键关系中获取所有值?

问题描述 投票:0回答:1

我有下一个型号:OrderOrderItem

class Order(models.Model):
    pass


class OrderItem(models.Model):
    order = models.ForeignKey(
        Order, related_name='order_item',
        verbose_name=_('order'), null=True,
        on_delete=models.SET_NULL,
        limit_choices_to={'enabled': True}
    )
    product_item = models.ForeignKey(
        Product, related_name='order_item',
        verbose_name=_('product item'), null=True, blank=True,
        on_delete=models.SET_NULL,
        limit_choices_to={'enabled': True}
    )

意见

def order_view(request):
    user_orders = Order.objects.filter(user=request.user)

如何获得每个订单的所有order_item值?

{% for order in orders %}
    {% for ord in orderitem.order_set.all %}
        123
    {% endfor %}    
{% endfor %}

我怎样才能获得product_item的所有order_item

django django-models django-templates django-views
1个回答
3
投票

您可以通过related_name访问OrderItems:

{% for order in orders %}
    {% for item in order.order_item.all %}
        {{ item.pk }}
    {% endfor %}    
{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.