2

I have a list of model objects:

just an example (I'm not really doing a list of all()):

class Tag(models.Model):
    name = models.CharField(max_length=50,primary_key=True)
    #Some other fields....

    def __str__(self):
        return self.name

mylist = list(Tag.objects.all())

What's the best way of converting this to a list of strings ?
Do I have to iterate the list ?

I was doing something like:

newList = [ t.str() for t in mylist ]

Any better way ?

2
  • I think that if you really need a list of strings your code is fine. The question is, do you really need to convert to string? Remember that the templates user your __str__ or __unicode__ method so you do not need to pass them strings. You could also do [x.name for x in mylist], that may be a little faster. Commented May 4, 2011 at 21:41
  • It's not for a template... I'm getting a list of items with a complex query. then i need to get one of the fields as string and pass that list to another query Commented May 5, 2011 at 4:41

1 Answer 1

3

This

newList = [ str(t) for t in mylist ]

or

newList = map( str, myList )

But generally, we don't bother. We just leave it to the template to convert the query set into strings when the template is rendered.

Sign up to request clarification or add additional context in comments.

2 Comments

How do you render it in the template ?
The usual way: {% for item in the list %}{{item}}{% endfor %} The items are automatically converted to strings in the template. You should see this: docs.djangoproject.com/en/1.3/ref/templates/api

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.