我总是在Question.objects.filter()
使用过滤器
但这一次,我想使用过滤器从类中获取值,如:
class Expense():
amount = ''
currency = ''
date = ''
这是我的方法:
def get_expense_list(self, taskId):
#get expense list
self.expenseList = [Expense()]
# get all activity from task
self.activiytList = Activity.objects.filter(task_id=taskId)
for activity in self.activiytList:
try:
self.expenseList.filter(currency=activity.expense_currency, self.expenseList)
self.expenseList.amount = self.expenseList.expense.amount + activity.expense
except:
newExpense = Expense()
newExpense.currency = activity.currency
newExpense.amount = activity.amount
newExpense.date = activity.date
self.expenseList.append(newExpense)
我正在从活动列表中创建费用清单。在activity.model
中,有些对象是:
amount = models.DecimalField(max_digits=16, decimal_places=2)
currency = models.CharField(max_length=5)
date = models.DateField()
我想在费用清单中显示,如果货币和日期相同,金额将会添加,如果没有现有的日期和货币,则会append()
。
请帮帮我。
答案 0 :(得分:0)
列表中没有filter()
方法,因此您编写的代码无效。
所以,忽略你的代码,如果你想要的是:
我想在费用清单中显示,如果他们的货币和日期相同,金额将会增加,如果没有现有的日期和货币,它会追加()。
那么你想要做的事情是:
def get_expense_list(self, taskId):
self.expenseList = []
self.activityList = Activity.objects.filter(task_id=taskId)
for activity in self.activityList:
# all existing expenses for this currency and date
comparisonFunc = lambda x: x.currency == activity.currency and x.date == activity.date
expenses = filter(comparisonFunc, self.expenseList)
# if there are no expenses, create a new
if len(expenses) == 0:
expense = Expense()
expense.amount = activity.amount
expense.date = activity.date
expense.currency = activity.currency
self.expenseList.append(expense)
# otherwise, increase the amount for expenses that were matching
else:
for expense in expenses:
expense.amount += activity.amount
您也可以使用聚合在数据库中执行所有这些操作。