我有这个ModelAdmin类:
class CoachAdmin(admin.ModelAdmin):
...
actions = ['add_50_credits']
list_display = ('number_of_clients_bought')
def get_queryset(self, request):
qs = super(CoachAdmin, self).queryset(request)
qs = qs.annotate(models.Count('sale'))
return qs
def number_of_clients_bought(self, obj):
return Sale.objects.filter(coach=obj).count()
number_of_clients_bought.admin_order_field = 'sale__count'
number_of_clients_bought.short_description = 'Clients bought'
def add_50_credits(self, request, queryset):
queryset.update(account_balance=F('account_balance') + 50)
self.message_user(request, "50 credits added.")
在添加get_queryset和number_of_clients_bought函数之前,add_50_credits操作正常工作。但是现在当我尝试使用add_50_credits操作时,它会抛出这个错误:
OperationalError at /admin/people/coach/
only a single result allowed for a SELECT that is part of an expression
这一行引发了错误:
queryset.update(account_balance=F('account_balance') + 50)
请向我解释我做错了什么以及如何解决这个问题,因为现在我很难过。提前谢谢!
答案 0 :(得分:0)
猜猜....输入add_50_credit时,你的查询集大于1。
尝试在那里调试它,在输入func或pdb(beark point)时打印它,
怎么样....
def add_50_credits(self, request, queryset):
for q in queryset:
q.update(account_balance=F('account_balance') + 50)
self.message_user(request, "50 credits added.")
只需确保消息func获得正确的请求
答案 1 :(得分:0)
原来这是一个问题,SQLite无法找出因连接而更新的字段。
记录在案here.
我通过在操作中添加.values('id')来解决它,如下所示:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name abc
请注意,'id'是Django模型的默认主键。如果您有特定型号的其他主键,则可能需要使用该键。