0

I have a query

 messages = Message.objects.all()

I want to create a Create a comma separated string of all numbers from message.number

This is what I have tried:

number = ""
for obj in messages:
     number = number + "," + obj.number

How can I do this? PS this string can be VERY long over 400,000 numbers!

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
GrantU
  • 6,325
  • 16
  • 59
  • 89

2 Answers2

8

Use join():

",".join(str(msg.number) for msg in Message.objects.all())

Also, since you have a large queryset, consider splitting your results into chunks using a queryset iterator. For more info see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    This won't work if `msg.number` is actually a _number_, better cast it to string first; and you also have extra `( )` in there. – Burhan Khalid Aug 27 '13 at 11:32
1

Use str.join:

number = ','.join(messages)
Sjoerd
  • 74,049
  • 16
  • 131
  • 175