这就是我的model.py的样子。第三个字段(标签)应该包含多个值(因为新闻帖可以有多个标签),就像列表一样。如何实现?
from django.db import
class News(models.Model)
heading=models.CharField(max_length=50)
post_date=models.DateTimeField('Date Posted')
labels=models.???
答案 0 :(得分:0)
class ListField(models.TextField, metaclass=models.SubfieldBase):
description = "ListField store List of element"
SPLIT_CHAR= ';'
def __init__(self, *args, list_choices=None, **kwargs):
super(ListField, self).__init__(*args, **kwargs)
if list_choices is None:
list_choices = []
self.list_choices = list_choices
def to_python(self, value):
res = []
if value is None:
res = []
if isinstance(value, list):
res = value
if isinstance(value, builtins.str):
res = value.split(self.SPLIT_CHAR)
try:
if "[" in value and "]" in value:
res = eval(value)
except:
pass
return res
def get_prep_value(self, value):
if value is None or value == "":
return None
res = self.SPLIT_CHAR.join(value)
return res
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
def formfield(self, **kwargs):
return forms.MultipleChoiceField(choices=self.list_choices)
然后创建像这样的List字段。
from django.db import
class News(models.Model)
heading=models.CharField(max_length=50)
post_date=models.DateTimeField('Date Posted')
labels=ListField()