ManyToManyField的应用实例
1,简单示例:
class TestAdmin(admin.ModelAdmin):
def get_some_value(self):
return ", " . join([x.__str__() for x in self.manytomany_field.all()])
list_display(get_some_value)
get_some_value.short_description = 'Title' #sets column header to Title
2,实际应用代码:
#显示选择的合作区域,此处的city为本模型下manytomany字段
def post_tag(self):
return [pt.__str__() for pt in self.city.all()]
post_tag.short_description = '标签'
filter_horizontal = ('tags',) # 多对多,穿梭框(横向双排,左边选到右边)
3,将ManyToManyField显示为复选框
from django.db import models
from django.contrib import admin
from django.forms import CheckboxSelectMultiple
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
4,还有2种方法可尝试:
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if db_field.name == 'your field name':
kwargs['widget'] = form_widgets.CheckboxSelectMultiple()
kwargs['help_text'] = ''
return db_field.formfield(**kwargs)
def get_form(self, request, obj=None, **kwargs):
form = super(VNodeAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['node_type'].widget = forms.CheckboxSelectMultiple()
return form
5,给复选框的内容加上CSS样式:
def post_tag(self):
result = []
for pt in self.city.all():
result.append(f'''
<span class="el-tag el-tag--small el-tag--success el-tag--dark">{pt.name} </span>
'''
)
return format_html("".join(result))
样式具体如图:
本文来自博客园,作者:super_ip,转载请注明原文链接:https://www.cnblogs.com/superip/p/17268740.html