访问时将字段拆分为数组

时间:2010-07-06 15:58:49

标签: python django django-models

我的Django模型看起来像这样:

class Categories(models.Model):
    """
    Model for storing the categories
    """
    name = models.CharField(max_length=8)
    keywords = models.TextField()
    spamwords = models.TextField()
    translations = models.TextField()

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = _('Category')
        verbose_name_plural = _('Categories')

字段keywordsspamwordstranslations包含大量以逗号分隔的文本。有人可以告诉我如何在模型中编写一个函数,对于特定的fieldname,返回一个列表的值,以便我可以像这样访问它:

cat = Categories.objects.get(id=1)
print cat.keywords.to_array()

...它返回字段数据,拆分成数组。 (分裂位非常简单,我知道如何做到这一点 - string.split(',')

由于

2 个答案:

答案 0 :(得分:1)

您可以轻松地将实例方法添加到Categories类,如下所示:

class Categories(models.Model):
   ... rest of your definition ...

   def get_spamwords_as_list(self):
       return self.spamwords.split(',')

您可以像这样使用它:

cat = Categories.objects.get(id=1)
print cat.get_spamwords_as_list()

但我对您的基础数据模型感到好奇 - 为什么不使用ManyToManyField来为您的类别建模?

更新:添加替代通用版本:

def get_word_list(self, name):
    if name in ['keywords', 'spamwords', 'translations']:
        return getattr(self, name).split(',')

# or even
def __getattr__(self, name):
    if name[-5:] == '_list' and name[:-5] in ['keywords', 'spamwords', 'translations']:
        return getattr(self, name[:-5]).split(',')
    else
        raise AttributeError

cat = Categories.get(pk=1)
cat.get_word_list('keywords')  # ['word 1', 'word 2', ...]
cat.keywords_list              # ['word 1', 'word 2', ...] with 2nd approach
cat.keywords                   # 'word 1, word 2' -- remains CSV

答案 1 :(得分:0)

我是这样做的:

class Categories(models.Model):
    """
    Model for storing the categories
    """
    name = models.CharField(max_length=8)
    keywords = models.TextField()
    spamwords = models.TextField()
    translations = models.TextField()

    def __unicode__(self):
        return self.name

    def __getattribute__(self, name):
        if name not in ['keywords', 'spamwords', 'translations']:
            return object.__getattribute__(self, name)
        else:
            return object.__getattribute__(self, name).split(',')

    class Meta:
        verbose_name = _('Category')
        verbose_name_plural = _('Categories')