django 中的网上商店。如何按用户筛选订单?

Internet shop in django. How to filter orders by user?

对于我的项目,我编写了帐户、购物车、订单和商店应用程序。

order/models:

from django.db import models
from shop.models import Product


class Order(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()
    address = models.CharField(max_length=250)
    postal_code = models.CharField(max_length=20)
    city = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    paid = models.BooleanField(default=False)

    class Meta:
        ordering = ('-created',)

    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',
                              on_delete=models.CASCADE)
    product = models.ForeignKey(Product, related_name='order_items',
                                on_delete=models.CASCADE)
    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

account/models为空

account/views:

from django.contrib.auth import login as auth_login
from django.shortcuts import render, redirect
from .forms import SignUpForm
from orders.models import OrderItem, Order
from django.contrib.auth.decorators import login_required


def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth_login(request, user)
            return redirect('/')
    else:
        form = SignUpForm()
    return render(request, 'accounts/signup.html', {'form': form})


@login_required
def account(request):
    my_orders = Order.objects.all()
    order_items = OrderItem.objects.all()
    return render(request, "accounts/my_acc.html",
                  {"my_orders": my_orders, "order_items": order_items})

正如您在帐户功能中看到的那样,我获得了所有订单,但我不知道如何为用户过滤订单。我想要的是 - 当用户输入他的帐户时,他可以看到他以前的所有订单。

我该怎么做?

您首先需要将您的 OrderUser 相关联:

from django.contrib.auth import get_user_model

User = get_user_model()

class Order(models.Model):

    user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='orders')
    # insert other fields here

请参阅 referencing the user model 了解这里发生的事情。

现在您在 OrderUser 之间建立了关系,这意味着您可以像这样过滤给定用户的订单:

def account(request):
    my_orders = Order.objects.filter(user=request.user)

首先创建订单时,您当然需要将 OrderUser 相关联 - 无论创建订单的代码都需要这样做。