开发者

Getting values from the database as list

I have the Model:

class TreeComment(models.Model):
   parent = models.ForeignKey('self', null=True, blank=True, verbose_name='Parent') 
   title = models.TextField(_('Title'), blank=True)

I want to call TreeComment.objects.all() and put result values into some list:

for e in TreeComment.objects.all():
    some_list += e

Is it possible to put all values into the list including the parent value?

Not whole parent object but id only (to prevent unnecessary DB calls and joins). After that I will process开发者_如何学JAVA it without DB calls inside the bussiness logic.


If you are looking to pull the query back as a list try

TreeComment.objects.values_list()

which would return [(1, u'some title'), ...] 1 being parent id and u'some title' being title's value

values_list docs


I'm thinking 2 solutions

1) You create a method get_parent(self) inside TreeComment class. Then in your themplate you could do {% for elem in some_list %}{{ elem.get_parent.whatever_method }}{% endfor %}

2) You could use a custom structure containing (, title) and the populating method reads from your TreeComment.objects.all(), gets the parent and the title and populates your list with your custom couples

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜