创建购物历史

时间:2015-05-17 12:54:24

标签: django django-models django-views

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

具有平衡和撤销功能的用户模型:

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

orderstatus应用,我在其中为订单历史记录制作了模型OrderHistory

class OrderHistory(models.Model):
    class Meta():
        db_table = 'order_history'

    user = models.ForeignKey(User)
    article = models.ForeignKey(Article)
    purchase_date = models.DateTimeField(auto_now_add=True)

在用户点击“购买”后,他使用POST启动action,然后views.py应用中的orderstatus

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_balance中有足够的钱,如果是,请创建withdraw。因此,如果购买完成,我需要以OrderHistory模式保存该购买...之前不要执行此类任务......我该怎么做?

2 个答案:

答案 0 :(得分:2)

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

  

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

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)

答案 1 :(得分:0)

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

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)