views:

87

answers:

2

hello I want to generate a list using my django model

say I have these model:

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

and such a list

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

Doesn't seem to work, what am I doing wrong?

+2  A: 
server_ips = [i.ip for i in AlarmServer.objects.all()]

Should work (I just added a space). I've tried this as below

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']
Mez
I think you can tag `.iterator()` to the end of this queryset for memory savings. `AlarmServer.objects.all().iterator()`. Check out: http://www.djangoproject.com/documentation/models/lookup/
thornomad
+2  A: 

values_list

server_ips = [i[0] for i in AlarmServer.objects.values_list('ip')]
slav0nic
No idea if this is what the OP wants, but you can avoid the list comprehension in your example by simply doing `AlarmServer.objects.values_list('ip', flat=True)`
Daniel Roseman