【问题标题】:How to use django autocomplete with field related to ContentType?如何使用 django 自动完成与 ContentType 相关的字段?
【发布时间】:2018-05-01 00:09:23
【问题描述】:
美好的一天,我正在将 django-autocomplete-light 3.2.10 用于与 ContentType 模型相关的字段,并在 django admin 中使用 ForeignKey 关系。我需要过滤ContentType 的名称,但它实际上是@property。那么有没有办法做到这一点?
更新:我实际上需要过滤 ContentType 而不是模型的 verbose_name 而不是 name。
【问题讨论】:
标签:
django
django-autocomplete-light
【解决方案1】:
我找到了答案,它有点难看,但很有效。
class TransactionAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
user = self.request.user
if user.is_authenticated() and user.is_staff:
if self.q:
models = apps.get_models()
result_list = []
for model in models:
if self.q in model._meta.verbose_name:
result_list.append(
ContentType.objects.get_for_model(model)
)
return result_list
else:
return ContentType.objects.all()
else:
return ContentType.objects.none()