Django2+xadmin 设置 relfield_style
2018-07-26 本文已影响316人
大壶
教程讲解
下拉框搜索:
relfield_style ='fk-ajax'
当有外键指向他,会以ajax方式加载
数据量过大时很有用
实际情况
我的环境是python3.6+Django2.0.7+xadmin
除了过滤器中加入的字段有效果,在表单录入界面并没有什么用
这个问题的原因是Django2中ForeignKey和Django1不一样造成的
解决办法
修改 xadmin/views/edit.py
# if hasattr(db_field, "rel") and db_field.rel:
if hasattr(db_field, "rel") and db_field.rel:
related_modeladmin = self.admin_site._registry.get(db_field.rel.to)
改为
# if hasattr(db_field, "rel") and db_field.rel:
if hasattr(db_field, "remote_field") and db_field.remote_field:
related_modeladmin = self.admin_site._registry.get(db_field.remote_field.model)
修改 xadmin/plugins/relfield.py
def label_for_value(self, value):
key = self.rel.get_related_field().name
try:
obj = self.rel.to._default_manager.using(
self.db).get(**{key: value})
return '%s' % escape(Truncator(obj).words(14, truncate='...'))
except (ValueError, self.rel.to.DoesNotExist):
...
...
def get_field_style(self, attrs, db_field, style, **kwargs):
# search able fk field
if style in ('fk-ajax', 'fk-select') and isinstance(db_field, models.ForeignKey):
if (db_field.remote_field.to in self.admin_view.admin_site._registry) and \
self.has_model_perm(db_field.remote_field.to, 'view'):
db = kwargs.get('using')
return dict(attrs or {},
widget=(style == 'fk-ajax' and ForeignKeySearchWidget or ForeignKeySelectWidget)(db_field.remote_field, self.admin_view, using=db))
改为
def label_for_value(self, value):
key = self.rel.get_related_field().name
try:
# obj = self.rel.to._default_manager.using(
obj = self.rel.model._default_manager.using(
self.db).get(**{key: value})
return '%s' % escape(Truncator(obj).words(14, truncate='...'))
except (ValueError, self.rel.model.DoesNotExist):
...
...
def get_field_style(self, attrs, db_field, style, **kwargs):
# search able fk field
if style in ('fk-ajax', 'fk-select') and isinstance(db_field, models.ForeignKey):
if (db_field.remote_field.model in self.admin_view.admin_site._registry) and \
self.has_model_perm(db_field.remote_field.model, 'view'):
db = kwargs.get('using')
return dict(attrs or {},
widget=(style == 'fk-ajax' and ForeignKeySearchWidget or ForeignKeySelectWidget)(db_field.remote_field, self.admin_view, using=db))