django的网上商店。如何按用户过滤订单?

时间:2018-03-15 11:23:57

标签: django orders webshop

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

顺序/型号:

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

帐户/模型为空

帐户/观点:

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})

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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

首先,您需要将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相关联 - 无论创建订单的代码是什么,都需要这样做。