我使用Django遇到了一个问题。我正在创建一个跟踪存款和取款的财务应用程序。不过我使用模型遇到了一个问题。这是相关代码
Views.py
from django.shortcuts import render
from .models import Transaction
# Create your views here.
class Transaction:
def __init__(self, name, description, location, amount):
self.name = name
self.description = description
self.location = location
self.amount = amount
def sum(totals):
sum = 0
for i in range(len(totals)):
if totals[i].name.lower() == 'deposit':
sum += totals[i].amount
else:
sum -= totals[i].amount
return sum
#transactions = [
# Transaction('Deposit', 'Allowance', 'Home', 25.00),
# Transaction('Withdrawl', 'Food', 'Bar Burrito', 11.90),
# Transaction('Withdrawl', 'Snacks', 'Dollarama', 5.71)
#]
def index(request):
transactions = Transaction.objects.all()
balance = sum(transactions)
return render(request, 'index.html', {'transactions':transactions, 'balance': balance})
Models.py
from django.db import models
# Create your models here.
class Transaction(models.Model):
name = models.CharField(max_length = 100)
description = models.CharField(max_length = 100)
location = models.CharField(max_length = 100)
amount = models.DecimalField(max_digits = 10, decimal_places = 2)
def __str__(self):
return self.name
admin.py
from django.contrib import admin
from .models import Transaction
# Register your models here.
admin.site.register(Transaction)
如果您需要查看并提前感谢,请告诉我
答案 0 :(得分:4)
您的视图中不需要第二个Transaction
课程。它隐藏了从模型导入的Transaction
模型/类。 删除它!
更重要的是,您还不需要自定义总和功能,请使用内置 sum
:
def index(request):
transactions = Transaction.objects.all()
balance = sum(t.amount if t.name=='deposit' else -t.amount for t in transactions)
...
答案 1 :(得分:0)
Transaction
文件中的views.py
课程会影响您的Transaction
模型。
Transaction
文件中的 views.py
是一个简单的python类(不是Django模型),要解决您的问题,需要将其从views.py
中删除