class tag(models.Model):
name = models.CharField(max_length=20, verbose_name='标签')
class book(models.Model):
name = models.CharField(max_length=50, verbose_name='书名')
tags = models.TextField(null=True, verbose_name='标签')
# 标签查询
def get_tag_list():
return tag.objects.values_list("name", "name")
# 表单类定义
class bookForm(forms.ModelForm):
tags = forms.MultipleChoiceField(label='标签', widget=widgets.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
super(cameraForm, self).__init__(*args, **kwargs)
# 保证每次初始化有最新的标签列表
self.fields['tags'].choices = get_tag_list()
# 由于会在数据库中存储为列表字符串,需在赋值时转回列表对象,才能在修改表单时识别原值
self.initial['tags'] = eval(self.initial['tags'])
class Meta:
model = book
exclude = []
# book扩展
class bookAdmin(admin.ModelAdmin):
search_fields = 'name', 'tags')
list_display = ( 'name', 'tags')
form = bookForm
# 注册到admin中
admin.site.register(book, bookAdmin)