1 In [1]: from apps.dormitory.models import Building 2 3 In [2]: buildings = Building.objects.values('number') 4 5 In [3]: buildings 6 Out[3]: [{'number': u'1'}, {'number': u'2'}, {'number': u'3'}, {'number': u'4'}, {'number': u'5'}] 7 8 In [4]: buildings_ = Building.objects.values_list('number') 9 10 In [5]: buildings_ 11 Out[5]: [(u'1',), (u'2',), (u'3',), (u'4',), (u'5',)] 12 13 In [6]: buildings_list = Building.objects.values_list('number', flat=True) 14 15 In [7]: buildings_list 16 Out[7]: [u'1', u'2', u'3', u'4', u'5']
class Building(models.Model): corporation = models.ForeignKey('company.Corporation', verbose_name=u'学校', related_name='buildings') number = models.CharField(u'楼栋编号', max_length=10, unique=True, db_index=True) create_time = models.DateTimeField(u'创建时间', auto_now_add=True)
从以上代码可以看出:
values方法可以获取number字段的字典列表。
values_list可以获取number的元组列表。
values_list方法加个参数flat=True可以获取number的值列表。