Django 创建购物历史

Django 创建购物历史,django,django-models,django-views,Django,Django Models,Django Views,我已经做了一个简单的商店,用户可以在他的个人资料中填写余额,然后可以购买一些数字内容。 现在我需要将所有购买的物品保存在一个单独的模型中,在那里我可以看到,谁买了什么,什么时候买的。。。 但我不明白,用户购买商品后如何在模型中保存这些信息。。。 这就是我现在拥有的 具有余额和取款功能的用户模型: class UserProfile(models.Model): class Meta(): db_table = 'userprofile' user = model

我已经做了一个简单的商店,用户可以在他的个人资料中填写余额,然后可以购买一些数字内容。 现在我需要将所有购买的物品保存在一个单独的模型中,在那里我可以看到,谁买了什么,什么时候买的。。。 但我不明白,用户购买商品后如何在模型中保存这些信息。。。 这就是我现在拥有的

具有余额和取款功能的用户模型:

class UserProfile(models.Model):
    class Meta():
        db_table = 'userprofile'

    user = models.OneToOneField(User)
    user_picture = models.ImageField(upload_to='users', blank=False, null=False, default='users/big-avatar.jpg')
    user_balance = models.DecimalField(default=0, max_digits=10, decimal_places=2)

    def withdraw(self, amount):
        self.user_balance = self.user_balance - amount

    def can_purchase_amount(self, amount):
        if amount <= self.user_balance:
            return True

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u) [0])
在用户点击“购买”后,他启动了
POST
action
,然后在
orderstatus
应用程序中查看
views.py

def checkoutstatus(request, article_id):

    user_profile = UserProfile.objects.get(user=request.user)
    article = Article.objects.get(id=article_id)

    if user_profile.can_purchase_amount(article.article_cost):

        user_profile.withdraw(article.article_cost)
        user_profile.save()

        article.article_users.add(request.user)

    return redirect('/articles/get/%s' % article_id)

所以,该视图检查用户的
User\u余额中是否有足够的钱,如果有,则执行
draw
。因此,如果购买完成,我需要将该购买保存在
OrderHistory
模型中。。。以前从未做过这样的工作。。。如何才能做到这一点?

您可能应该添加如下创建OrderHistory对象:

OrderHistory.objects.create(user=request.user,article=article)


在我的应用程序中,我写了一个视图

def orderhistory(request):
order_histroy = Order.objects.filter(user=request.user)
template = "users/orders.html"
context = {
    "order_histroy": order_histroy
}
return render(request, template, context)

哦。。。不要以为,有些事情有时候这么简单…)谢谢。
def checkoutstatus(request, article_id):

    user_profile = UserProfile.objects.get(user=request.user)
    article = Article.objects.get(id=article_id)

    if user_profile.can_purchase_amount(article.article_cost):

        user_profile.withdraw(article.article_cost)
        user_profile.save()

        article.article_users.add(request.user)

        OrderHistory.objects.create(user=request.user, article=article)

    return redirect('/articles/get/%s' % article_id)
def orderhistory(request):
order_histroy = Order.objects.filter(user=request.user)
template = "users/orders.html"
context = {
    "order_histroy": order_histroy
}
return render(request, template, context)