时间:2021-05-22
实现了在一个字段存储以逗号分隔的字符串,返回一个相应的列表
复制代码 代码如下:
from django import forms
from django.db import models
from django.utils.text import capfirst
from django.core import exceptions
class MultiSelectFormField(forms.MultipleChoiceField):
widget = forms.CheckboxSelectMultiple
def __init__(self, *args, **kwargs):
self.max_choices = kwargs.pop('max_choices', 0)
super(MultiSelectFormField, self).__init__(*args, **kwargs)
def clean(self, value):
if not value and self.required:
raise forms.ValidationError(self.error_messages['required'])
# if value and self.max_choices and len(value) > self.max_choices:
# raise forms.ValidationError('You must select a maximum of %s choice%s.'
# % (apnumber(self.max_choices), pluralize(self.max_choices)))
return value
class MultiSelectField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "CharField"
def get_choices_default(self):
return self.get_choices(include_blank=False)
def _get_FIELD_display(self, field):
value = getattr(self, field.attname)
choicedict = dict(field.choices)
def formfield(self, **kwargs):
# don't call super, as that overrides default widget if it has choices
defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name),
'help_text': self.help_text, 'choices': self.choices}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
return MultiSelectFormField(**defaults)
def get_prep_value(self, value):
return value
def get_db_prep_value(self, value, connection=None, prepared=False):
if isinstance(value, basestring):
return value
elif isinstance(value, list):
return ",".join(value)
def to_python(self, value):
if value is not None:
return value if isinstance(value, list) else value.split(',')
return ''
def contribute_to_class(self, cls, name):
super(MultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
func = lambda self, fieldname = name, choicedict = dict(self.choices): ",".join([choicedict.get(value, value) for value in getattr(self, fieldname)])
setattr(cls, 'get_%s_display' % self.name, func)
def validate(self, value, model_instance):
arr_choices = self.get_choices_selected(self.get_choices_default())
for opt_select in value:
if (int(opt_select) not in arr_choices): # the int() here is for comparing with integer choices
raise exceptions.ValidationError(self.error_messages['invalid_choice'] % value)
return
def get_choices_selected(self, arr_choices=''):
if not arr_choices:
return False
list = []
for choice_selected in arr_choices:
list.append(choice_selected[0])
return list
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
作用: GROUP_CONCAT函数可以拼接某个字段值成字符串,默认的分隔符是逗号,即",", 如果需要自定义分隔符可以使用SEPARATOR 如:SEL
通过特性给一个枚举类型每个值增加一个字符串说明,用于打印或显示。自定义打印特性[AttributeUsage(AttributeTargets.Field)]p
实例向用户自定义函数发送数组中的值,并返回一个字符串:定义和用法array_reduce()函数向用户自定义函数发送数组中的值,并返回一个字符串。注释:如果数组
C#中有一个字符串拆分函数String.Split(),可以用于将一个字符串,拆分为一个字符串数组。在拆分的时候,需要一个拆分的“分隔符”。这个“分隔符”可以是
本文实例讲述了php实现将字符串按照指定距离进行分割的方法。分享给大家供大家参考。具体如下:将一个字符串每隔三个字符添加一个逗号,例如把字符串123456789