Python: Model.objects.all() - how to iterate through it using POST checkboxes

0 votes
asked Sep 11, 2017 by greg-bialowas

I have been building a CSV export using Python/Django. While sending all items listed in the change list everything works like a charm.

Now, I've been trying to use Action dropdown and export only those items selected via the checkboxes, but I cannot make it work.

My current code, the one that works even with the Action dropdown yet exporting ALL items, regardless of what was checked:

def export_this_list(self, request, queryset):
    """Generates participants list in Excel sheet."""

    csv_elements = Enrolment.objects.all().order_by('-training__date')
    for elem in csv_elements:

When csv_elements is swapped with request.POST.getlist obviously nothing works.

def export_this_list(self, request, queryset):
    """Generates participants list in Excel sheet."""

    csv_elements = request.POST.getlist('_selected_action')

or

    csv_elements = []
    for o in request.POST.getlist('_selected_action'):

Question: what is the syntax to combine my Model with the POST action?

1 Answer

0 votes
answered Sep 11, 2017 by daniel-roseman

When you do csv_elements = Enrolment.objects.all() you retrieve a set of Enrolment objects from the database that you subsequently iterate over.

But when you do csv_elements = request.POST.getlist('_selected_action') you have a list of IDs. You don't have Enrolment objects; they are still in the database, and you haven't done anything to get them. The IDs are the keys of the objects in the database, but as far as your code is concerned so far they're just numbers.

You need to actually go to the database to get those objects. Here's one way of doing that:

selected_ids = request.POST.getlist('_selected_action')
csv_elements = Enrolment.objects.filter(id__in=selected_ids)
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...