如何在Django模型中添加列表数据类型?

时间:2014-08-28 00:51:49

标签: django django-models django-forms

这就是我的model.py的样子。第三个字段(标签)应该包含多个值(因为新闻帖可以有多个标签),就像列表一样。如何实现?

    from django.db import 

    class News(models.Model)
        heading=models.CharField(max_length=50)
        post_date=models.DateTimeField('Date Posted')
        labels=models.???       

1 个答案:

答案 0 :(得分:0)

Django没有提供默认列表字段,所以你必须从继承TextField创建自己的列表字段,我发布了一个示例代码看看。

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()