简体   繁体   中英

django convert query set to array of list

How can I convert a QuerySet returned to an array of string?

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

您可以使用values_list()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM