我的模型如下
class Loan(models.Model):
loan_value = models.IntegerField()
channel_seller = models.ForeignKey(ChannelSeller, on_delete=models.CASCADE)
class ChannelSeller(models.Model):
LEVEL_CHOICES = (
('1','Business Consultants'),
('2','Unit Managers'),
('3','Account Managers'),
('4','Branch Managers'),
)
level = models.CharField(max_length=2, choices = LEVEL_CHOICES, null = True, blank = True)
pin_no = models.CharField(max_length=255)
unit_manager = models.ForeignKey('self', limit_choices_to = {"level": '2'}, on_delete=models.DO_NOTHING, null = True, blank = True, related_name='unit_manager_2')
贷款可以由business_consultant或unit_manager创建。每个业务_顾问都将有一个unit_manager,但是,unit_maanager将把unit_manageer作为空白
话虽如此,
我正试图使用case、when和按unit_manager字段对查询进行排序
transactions = Loan.objects.annotate(unit_manager_pin = Case(When('channel_seller__level' == '2', then='channel_seller_pin_no'), When('channel_seller__level' == '1', then='channel_seller__unit_manager__pin_no'))).filter(channel_seller__level__in = ['1','2']).order_by('channel_seller__level')
然而,此查询向我抛出错误__init__() takes either a Q object or lookups as keyword arguments
需要应用的条件就像一个过滤器,还可以使用F函数获取值。试试这个。
transactions = Loan.objects.annotate(unit_manager_pin = Case(When(channel_seller__level='2', then=F('channel_seller__pin_no')), When(channel_seller__level='1', then=F('channel_seller__unit_manager__pin_no')))).filter(channel_seller__level__in = ['1','2']).order_by('channel_seller__level')
您正在对一个查询进行编码,以便由DBM执行。您不能在该上下文中使用Python代码('channel_seller__level' == '2'
(。请参阅有关条件表达式的文档。
请将您的代码格式化为易读的格式!使用括号内的换行符继续。
在这种情况下,您只需将==
更改为=
,但了解原因很重要。When
的自变量与.filter
的自变量类似。因此,要测试大于,它将是When( field__gt = 2, ...)
您还需要使用F
来引用数据库中的值。如果没有F
,它将(可能,不确定(是一个错误。(如果你想要一个固定的值,你可以使用Value('fixed-value')
(
transactions = Loan.objects.annotate(unit_manager_pin =
Case(When('channel_seller__level' = '2',
then=F('channel_seller_pin_no')),
When('channel_seller__level' = '1',
then=F('channel_seller__unit_manager__pin_no'))
)
).filter(
...