我在使用 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)
如果您需要查看任何其他代码,请告诉我,并提前致谢
最佳答案
您的 View 中不需要第二个 Transaction
类。它隐藏了从您的模型导入的 Transaction
模型/类。 删除 吧!
更重要的是,您也不需要自定义 sum 函数,使用内置的 sum
:
def index(request):
transactions = Transaction.objects.all()
balance = sum(t.amount if t.name=='deposit' else -t.amount for t in transactions)
...
关于python - views.py : type object 'Transaction' has no attribute 'objects' 中的 AttributeError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47045013/