简体   繁体   中英

How to append a key value of dictionary to a list

I have a function like this:

def eventcateg_detail(request):
    ca = EventTypeCategory.objects.values()
    for i in range(0, len(ca)):
       pk_sub = ca[i]['sub_categ_id']
       if (pk_sub!=None):
          category = EventTypeCategory.objects.get(id = pk_sub)
          category = category.name
    return render(request,"events/categ.html",{
       'obj': ca
        })

Definition of above function:

Fist i am getting a dictionary in ca variable ie

[{'Message_slug': u'critical', 'sub_categ_id': None, 'user_id': 1L, 'id': 190L, 'name': u'Critical'}, {'Message_slug': u'information', 'sub_categ_id': 190L, 'user_id': 1L, 'id': 192L, 'name': u'Information'}]

Now i want to get a value defining in sub_categ_id for each content. I got this in pk_sub variable. As you can see that pk_sub is returning an id (which is foreign key to itself). I want to get all these values which pointing to that pk_sub. I am also getting this :

Critical
Information
Amit Pal

Now i want to append this category.name into a list. So that i can easily pass to my template. How should i do this?

I tried by putting following code at next line:

categories = categories.append(category)

but it didn't work :(

Two things:

  1. You can iterate over list directly, rather than by index: for category in ca: . In the body of that loop, category will be bound to each item in ca.
  2. You never define categories , so you cannot append to it; in any case, list.append returns None , and destructively modifies the list, so you would have to omit the assignment.

Finally, as a matter of style one usually uses x is not None rather than != when testing for None.

Update: Note @agf's comment, which describes the proper way to use the Django ORM to perform this task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM