我正在尝试写网络商店,我有一个模型Order
:
class Order(models.Model):
state_choices = ('ACTIVE', 'COMPLETED', 'FROZEN')
order_date = models.DateTimeField(auto_now_add=True)
delivery_time = models.CharField(max_length=100)
address_city = models.CharField(max_length=40)
address_street = models.CharField(max_length=40)
address_building = models.CharField(max_length=40)
state = models.CharField(max_length=200, default='ACTIVE')
products = models.ForeignKey(OrderProduct)
client = models.ForeignKey(CustomUser)
OrderProduct
:
class OrderProduct(models.Model):
product = models.ForeignKey(Product)
product_ammount = models.IntegerField()
如您所见,用户可以添加订购不同产品和每种产品的不同数量。因此,对于当前型号,我可以添加订购只有一种类型的产品。然后我用下一个方法重写它:
class Order(models.Model):
state_choices = ('ACTIVE', 'COMPLETED', 'FROZEN')
order_date = models.DateTimeField(auto_now_add=True)
delivery_time = models.CharField(max_length=100)
address_city = models.CharField(max_length=40)
address_street = models.CharField(max_length=40)
address_building = models.CharField(max_length=40)
state = models.CharField(max_length=200, default='ACTIVE')
client = models.ForeignKey(CustomUser)
class OrderProduct(models.Model):
product = models.ForeignKey(Product)
order = models.ForeignKey(Order)
product_ammount = models.IntegerField()
在view
中,当我需要获取用户的订单时,我只需执行下一步:Order.objects.get(client=request.user).orderproduct_set
但我认为这不正确。如何重建这些模型以获得理想的结果?
答案 0 :(得分:2)
在我看来,第二种方法完全没问题。
问题中的一个小错误是查询使用get()
而不是filter()
。一旦一个用户拥有多个订单,这将导致异常。
所以,而不是get()
,它将是:
orders = Order.objects.filter(client=request.user)
for order in orders:
print order.orderproduct_set.all()
要在模板中使用它(来自评论的问题),传递订单就足够了:
views.py
class MyView(View):
def get(self, request):
ctx = {
'orders': Order.objects.filter(client=request.user)
}
return render(request, 'my/template.html', ctx)
my / template.html
{% for order in orders %}
{% for item in order.orderproduct_set.all %}
{{ item.product_amount }}x {{ item.product }}<br/>
{% endfor %}
{% endfor %}