简体   繁体   English

Django 管理列表视图阻止选择查找

[英]Django admin list view prevent choices lookup

class CustomerChoices(object):
    def expensive_lookup(self):
        ....

    def __iter__(self):
        yield from [(a.number, a.display) for a in self.expensive_lookup()]


class CustomerProfile(models.Model):
    account_number = models.IntegerField(unique=True, choices=CustomerChoices())
    ...
from django.contrib import admin
from .models import CustomerProfile


@admin.register(CustomerProfile)
class CustomerProfileAdmin(admin.ModelAdmin):
    list_display = ('account_number', ...)

Given above code, while I am happy with the add/edit admin to use the choices, how do I prevent django admin list view using the choices, so it doesn't make an expensive lookup?鉴于上面的代码,虽然我很高兴添加/编辑管理员使用这些选项,但我如何防止使用这些选项的 django 管理员列表视图,所以它不会进行昂贵的查找? Please note that I am aware of caching methods, but what if I just want to display the account number?请注意,我知道缓存方法,但如果我只想显示帐号怎么办?

Issue问题

When you put list_display = ('account_number', ...) in the model admin, Django fetching the "display value" by evaluating the choice iterable, and note that this "display value" doesn't belong to the database and hence the choice evaluation is a must-do thing.当你把list_display = ('account_number', ...)放在模型管理员中时,Django 通过评估选择迭代来获取“显示值” ,并注意这个“显示值”不属于数据库,因此选择评估是必须要做的事情。

Solutions解决方案

You have two choices,你有两个选择,

  1. Display the stored value from the database显示数据库中存储的值
  2. Keep things the same as before保持原样

For the first solution, you can define custom callable list methods as对于第一个解决方案,您可以将自定义可调用列表方法定义为

@admin.register(CustomerProfile)
class CustomerProfileAdmin(admin.ModelAdmin):
    list_display = ('account_number_dup',)

    def account_number_dup(self, model_instance: CustomerProfile): return model_instance.account_number

JPG's answer seems OK for text or numbers.对于文本或数字,JPG 的答案似乎还可以。

But for booleans the value shown as result are "True" and "False" instead of images usually shown by Django.但是对于布尔值,显示为结果的值是“True”和“False”,而不是 Django 通常显示的图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM