我需要減去另一個整數形式並保存結果。它的某種付款方式。從來沒有這樣做之前,所以下面的代碼 - 它是我想要在我看來,要做到:摘自另一個整數並保存
def checkoutstatus(request, article_id):
if request.POST:
article = Article.objects.filter(id=article_id)
article.article_users.add(request.user)
balance = int(UserProfile.objects.filter(balance=user_balance))
cost = int(Article.objects.filter(cost=article_cost))
new_balance = balance - cost
article.save()
所以我第一次迷上了User
到Article
模型。然後,我需要從UserProfile
模型(擴展User
與ForeignKey
)字段user_balance
。減去Article
模型場article_cost
並保存結果返回給user_balance
......
正如你可以看到在上面的代碼中,我試圖讓減法,但我現在如何將結果保存回user_balance
?
此外,我是否需要int
轉換器,如果兩個模型中的兩個字段都已經工作爲IntegerField
?
我的應用程序article
:
from django.db import models
from django.contrib.auth.models import User
from django.db import models
class Article(models.Model):
class Meta():
db_table = 'article'
article_users = models.ManyToManyField(User)
article_title = models.CharField(max_length=200, blank=False, null=False)
article_content = models.IntegerField(choices=CONTENT_CHOICES, null=True, blank=True)
article_cost = models.IntegerField(default=0)
article_likes = models.IntegerField(default=0)
我的應用程序userprofile
:
import PIL
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.db import models
from article.models import Article
class UserProfile(models.Model):
user = models.OneToOneField(User)
user_picture = models.ImageField(upload_to='users', blank=False, null=False, default='users/big-avatar.jpg')
user_balance = models.IntegerField(default=0)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u) [0])
此外,我創建了一個應用程序orderstatus
,這需要保存的訂單歷史記錄在DB:
from django.db import models
from django.contrib.auth.models import User
from article.models import Article
class OrderHistory(models.Model):
class Meta():
db_table = 'order'
user = models.ForeignKey(User)
article = models.ForeignKey(Article)
purchase_date = models.DateTimeField(auto_now_add=True)
而且爲它寫一個視圖(你可以在開頭看到它後):
from django.shortcuts import render, render_to_response, redirect, Http404
from django.core.context_processors import csrf
from django.contrib import auth
from django.template import RequestContext
import datetime
from django.contrib.auth.models import User
from article.models import Article
from userprofile.models import UserProfile
def checkoutstatus(request, article_id):
if request.POST:
article = Article.objects.filter(id=article_id)
article.article_users.add(request.user)
balance = int(UserProfile.objects.filter(balance=user_balance))
cost = int(Article.objects.filter(cost=article_cost))
new_balance = balance - cost
article.save()
請提供您的'models.py',以便我們更好地瞭解範圍。另外,'user_balance'從哪裏來? – Hybrid
@Hybrid發佈更新。提供所有的數據,這可以幫助你,我認爲... –
'user_balance'沒有在你的視圖中提供! – Othman