D
D
darkglare2020-12-07 17:18:28
Django
darkglare, 2020-12-07 17:18:28

How to write a command correctly?

Hello. There are two models

from django.db import models
import django
from shop.models import Product
from django.contrib.auth.models import User
from datetime import datetime

class Order(models.Model):
    
    nickname = models.ForeignKey(User, on_delete=models.CASCADE, default=False)
    
    email = models.EmailField()
    
    postal_code = models.CharField(max_length=20)
    city = models.CharField(max_length=100)
    street = models.CharField(max_length=100, default="s")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    paid = models.BooleanField(default=False)
    


    class Meta:
        ordering = ('-created',)
        verbose_name = 'Заказ'
        verbose_name_plural = 'Заказы'

    def __str__(self):
        return 'Order {}'.format(self.id)

    def get_total_cost(self):
        return sum(item.get_cost() for item in self.items.all())


class OrderItem(models.Model):
    
    order = models.ForeignKey(Order, related_name='items')
    product = models.ForeignKey(Product, related_name='order_items')
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.PositiveIntegerField(default=1)
    

    def __str__(self):
        return '{}'.format(self.id)

    def get_cost(self):
        return self.price * self.quantity


The Order model stores information about who ordered and where to send the order.
The OrderItem model stores information about the ordered product: price, quantity, product name.

views.py

def my_orders(request):
    """Renders the about page."""
    orders = Order.objects.filter(nickname=request.user)
   
    
   
    assert isinstance(request, HttpRequest)
    return render(
        request,
        'app/my_orders.html', {'orders': orders,}
         )


There is a "My Orders" page, at the moment it renders information from the Order model using the line in views:
orders = Order.objects.filter(nickname=request.user)

and loop {% for order in orders %}in the template.

How do I access the OrderItem model?
If I access the Order model like this:
orders = Order.objects.filter(nickname=request.user)

Then to OrderItem...
order_item = OrderItem.objects.filter(что вот тут должно быть написано?
Or should I move in a different direction?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Melnikov, 2020-12-07
@Mi11er

It seems so, but read about the connections
f = Order.orderItem_set.all()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question