对于我的项目,我写了帐户,购物车,订单和商店应用程序。
订单/型号:
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})
正如您在帐户功能中看到的,我得到了所有订单,但我不知道如何为用户过滤订单。我想要的是 - 当用户输入他的帐户时,他可以看到他之前的所有订单。
我该怎么做?
您首先需要将Order
与User
相关联:
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
请参阅引用用户模型以了解此处正在发生的情况。
现在您有Order
和User
之间的关系,这意味着您可以像这样过滤给定用户的订单:
def account(request):
my_orders = Order.objects.filter(user=request.user)
当然,当首先创建订单时,您需要将Order
与User
相关联 - 创建订单的任何代码都需要这样做。