2017-10-31 10 views
3

私は初回のポスターです。私はDjangoを使用して問題に遭遇しました。私は預金と引き出しを追跡する金融アプリケーションを作成しています。私は、モデルを使用して問題にぶつかりました。ここでは、関連するコードviews.pyのAttributeError:タイプオブジェクト 'Transaction'には 'objects'という属性はありません

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) 

ルですあなたが見て、感謝する必要がある他のコードがある場合は、私は知っている

答えて

4

あなたのビューでは、2番目の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) 
    ... 
0

あなたviews.pyファイルを持っているTransactionクラスがあなたのTransactionモデルをシャドウ。 views.pyファイル内

Transactionは、単純なPythonクラス(ないDjangoのモデル)で、あなたの問題を解決するために、あなたはviews.py

からそれを削除する必要があります
関連する問題