django将查询设置转换为列表数组

时间:2011-11-10 19:28:10

标签: python django

如何将返回的QuerySet转换为字符串数组?

myWords = MyGroup.objects.get(name = "bla").allkeyword
# to
myWords = ["meltemi", "bla"]


class MyGroup(models.Model):
    name = models.CharField(max_length=32, unique=True)
    allkeyword = models.ManyToManyField('KeywordTag')
    def __unicode__(self):
        return '%s' % (self.name)

class KeywordTag(models.Model):
    name = models.CharField(max_length=32, unique=True)
    def __unicode__(self):
        return self.name

1 个答案:

答案 0 :(得分:5)

您可以使用values_list()

myWords = MyGroup.objects.get(name = "bla").allkeyword.values_list('name', flat=True)