Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating several records at once using Django

I want to create a list of records with checkboxes on the left side....kinda like the inbox in Gmail. Then if a user selects some or all of these checkboxes, then the selected record(s) can be updated (only one field will be updated BTW), possibly by clicking a button.

I'm stuck on how to do this though....ideas?

Display Code

{% for issue in issues %}    <tr class="{% cycle 'row1' 'row2' %}">       <td><input name="" type="checkbox" value="{{ issue.id }}" /></td>       <td>{{ issue.description }}</td>       <td>{{ issue.type }}</td>       <td>{{ issue.status }}</td>       <td>{{ issue.date_time_added|date:"d, M Y" }}</td>       <td>{{ issue.added_by }}</td>       <td>{{ issue.assigned_to }}</td>    </tr> {% endfor %} 
like image 831
Stephen Avatar asked Apr 30 '10 10:04

Stephen


People also ask

How do I update Django bulk records?

The best solutions I found are: a) use @transaction. atomic decorator, which improves performance by using a single transaction, or b) make a bulk insert in a temporary table, and then an UPDATE from the temporary table to the original one.

What is bulk create?

Bulk create lets you construct multiple data sources, derived signals, segments, traits, and other items with a single operation.

How Django knows to update VS insert?

The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.


1 Answers

Use the queryset update() method:

id_list = list_of_ids_from_checkboxes MyModel.objects.filter(id__in=id_list).update(myattribute=True) 

Your display HTML is missing a name value for the checkboxes. If you just have a single name across all checkboxes, then the list of IDs will be passed into a single POST variable, which you can get straight from request.POST (assuming you're submitting your form as a post, which you should be):

id_list = request.POST.getlist('checkboxname') 
like image 112
Daniel Roseman Avatar answered Sep 23 '22 04:09

Daniel Roseman