[英]AttributeError in views.py: type object 'Transaction' has no attribute 'objects'
I have run into an issue using Django. 我使用Django遇到了一个问题。 I am creating a finance app which tracks deposits and withdrawals.Unfourtanently I have run into an issue using models. 我正在创建一个跟踪存款和取款的财务应用程序。不过我使用模型遇到了一个问题。 Here is the relevant code 这是相关的代码
Views.py 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 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 admin.py
from django.contrib import admin
from .models import Transaction
# Register your models here.
admin.site.register(Transaction)
Let me know if there is any other code you need to look at and thanks in advance 如果您需要查看其他任何代码,请提前告知我们
You don't need a second Transaction
class in your views. 您的视图中不需要第二个Transaction
类。 It is shadowing the Transaction
model/class imported from your model. 它隐藏了从模型导入的Transaction
模型/类。 Remove it! 删除它!
More so, you also don't need a custom sum function, use the builtin sum
: 更重要的是,你也不需要自定义求和函数,使用内置sum
:
def index(request):
transactions = Transaction.objects.all()
balance = sum(t.amount if t.name=='deposit' else -t.amount for t in transactions)
...
The Transaction
class that you have in your views.py
file shadows your Transaction
model. views.py
文件中的Transaction
类会影响您的Transaction
模型。
Transaction
in views.py
file is a simple python class (not a Django model), to fix your issue, you need to remove it from views.py
views.py
文件中的Transaction
是一个简单的python类(不是Django模型),为了解决您的问题,您需要将其从views.py
删除
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.