我正在尝试向 Django 模型添加一个字段来表示电子邮件地址列表。我希望用户在管理中的表单中输入逗号分隔的地址列表,然后我的应用程序将解析该列表以发送一系列电子邮件。
我当前的实现涵盖了基本思想,但有很大的局限性。在管理中,如果我输入类似的字符串[email protected] /cdn-cgi/l/email-protection, [email protected] /cdn-cgi/l/email-protection
,然后它正确地将其写入数据库,如下所示[u'[email protected] /cdn-cgi/l/email-protection', u'[email protected] /cdn-cgi/l/email-protection']
。但管理员显示此序列化值而不是人性化字符串。更重要的是,如果我编辑并保存记录,而不进行任何更改,相同的转换会发生变化[u'[email protected] /cdn-cgi/l/email-protection', u'[email protected] /cdn-cgi/l/email-protection']
to [u"[u'[email protected] /cdn-cgi/l/email-protection'", u"u'[email protected] /cdn-cgi/l/email-protection']"]
.
如何将 python 列表表示形式转换回字符串以便在管理中使用?这就是目的吗value_to_string
方法还是我需要在其他地方进行转换?
我当前的自定义模型字段如下:
class EmailListField(models.TextField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if not value:
return
if isinstance(value, list):
return value
return [address.strip() for address in value.split(',')]
def get_db_prep_value(self, value):
if not value:
return
return ','.join(unicode(s) for s in value)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
这是基于SeparatedValuesField
此处描述:http://www.davidcramer.net/code/181/custom-fields-in-django.html http://www.davidcramer.net/code/181/custom-fields-in-django.html.