简体   繁体   中英

Django prefetch_related outputs None

I'm new to Django. I am making a simple store. Currently I am working on the Order section. Every Order has Order Items inside it. Every order item has some values and a product id.

What I am trying to display on the index.html, is the orders and its items inside it. However order.items always outputs order.OrderItem.None

views.py

class IndexView(generic.ListView):
    template_name = 'order/index.html'
    context_object_name = 'all_orders'

    def get_queryset(self):
        return Order.objects.all().prefetch_related('items')

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        return context

views.py

# Create your models here.
class Order(models.Model):
    user = models.ForeignKey(User, related_name='orders')
    created_at = models.DateTimeField(auto_now_add=True, null=True)

class OrderItem(models.Model):
    product = models.ForeignKey(Product)
    order = models.ForeignKey(Order, related_name='items')
    item_name = models.CharField(max_length=255, null=True, blank=True)
    item_price_in_usd = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)

    def __str__(self):
        return self.product.name

index.html

{% for order in all_orders %}
        <tr>
            <td>{{ order}}</td>
            <td>{{ order.created_at}}</td>
            <td>{{ order.items}}</td>
        </tr>
    {% endfor %}

Ok, I have found to solution. Apparently you have to add .all

{% for order in all_orders %}
        <tr>
            <td>{{ order}}</td>
            <td>{{ order.created_at}}</td>
            <td>
                {% for items in order.items.all %}
                    <td>{{ items.item_name}}</td>
                {% endfor %}
            </td>
        </tr>
    {% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM