django模型对象到python列表

时间:2009-10-28 08:27:41

标签: django django-models

我想使用我的django模型生成一个列表

说我有这些模特:

class AlarmServer(models.Model):
    ip = models.IPAddressField()

和这样的清单

server_ips = [i.ipfor i in AlarmServer.objects.all()]

似乎不起作用,我做错了什么?

2 个答案:

答案 0 :(得分:4)

server_ips = [i.ip for i in AlarmServer.objects.all()]

应该工作(我只是添加了一个空格)。我试过这个如下

mez@stupor % ./manage.py shell
Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from mysite_org.videos.models import Video
>>> url_list = [v.url for v in Video.objects.all()]
>>> url_list
[u'http://media.mysite.org/videos/sblug_jan2009.flv', u'http://media.mysite.org/videos/sblug_feb2009.flv', u'http://media.mysite.org/videos/phpwm_mar2009.flv', u'http://media.mysite.org/videos/sblug_may2009.flv', u'http://media.mysite.org/videos/sblug_june2009.flv', u'http://media.mysite.org/videos/sblug_sep2009.flv', u'http://media.mysite.org/videos/bugjam-oct-2009.flv']

答案 1 :(得分:3)

values_list

server_ips = [i[0] for i in AlarmServer.objects.values_list('ip')]