gpt4 book ai didi

Django在两个字段上组合过滤器

转载 作者:行者123 更新时间:2023-12-03 20:18:07 26 4
gpt4 key购买 nike

我对 Django 比较陌生。我在过滤数据时遇到问题。我有两个模型,如下所示:

Account(models.Model):
name = models.CharField(max_length=60)
hotel = models.ForeignKey(Hotel)
account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=30)

Transaction(models.Model):
account = models.ForeignKey(Account, related_name='transaction')
transaction_type = models.CharField(choices=TRANSACTION_TYPE, max_length=15)
description = models.CharField(max_length=100, blank=True, null=True)
date_created = models.DateTimeField(default=timezone.now)

ACCOUT_TYPE 是:
ACCOUNT_TYPE = (
(0, 'Asset'),
(1, 'Liabilities'),
(2, 'Equity'),
(3, 'Income'),
(4, 'Expense')
)

我想过滤账户类型为 Income的所有交易和 Expense在给定的日期范围内。如何在 Django 中组合这些过滤器?

我试过这样:
income_account = Account.objects.filter(account_type=3)
expense_account = Account.objects.filter(account_type=4)
transactions = Transaction.objects.filter(Q(
account=income_account,
date_created__gte=request.data['start_date'],
date_created__lte=request.data['end_date']
) & Q(
account=expense_account,
date_created__gte=request.data['start_date'],
date_created__lte=request.data['end_date'])).order_by('date_created')

但它不起作用。它引发以下错误:
  ProgrammingError: more than one row returned by a subquery used as an expression

最佳答案

income_accountexpense_account不是单个对象,它是一个对象列表。所以,而不是这个 account=income_account而这个 account=expense_account尝试使用 in :account__in=income_accountaccount__in=expense_account .
你也可以像这样简化查询集:

accounts = Account.objects.filter(Q(account_type=3) | Q(account_type=4))
transactions = Transaction.objects.filter(
account__in=accounts,
date_created__gte=request.data['start_date'],
date_created__lte=request.data['end_date']
).order_by('date_created')

关于Django在两个字段上组合过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42105347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com