Home > database >  How to get or show every object from newest to latest in Django
How to get or show every object from newest to latest in Django

Time:08-04

I'm pretty new to python and django. I was able to create an simple CRUD logic with template, but I have a small problem.

When I update a specific task and then querying all object from a model, the one that was updated is now queried on the last position (views.py below):

def create_task(request):
tasks = Task.objects.all()
if request.method == 'POST':
    task_id_update = request.POST.get('task_id_update')
    task_id_delete = request.POST.get('task_id_delete')
    if task_id_update:
        task = Task.objects.filter(id=task_id_update).first()
        task.finished = True
        task.save()
    elif task_id_delete:
        task = Task.objects.filter(id=task_id_delete).first()
        task.delete()
    else:
        form = TaskForm(request.POST)
        if form.is_valid():
            task = form.save(commit=False)
            task.author = request.user
            task.save()
            return redirect('/create_task')
form = TaskForm()
return render(request, 'main/create_task.html', {'form': form, 'tasks': tasks})

And I want to render it on a ONE-PAGE like template, and this is what I did in my html:

<table >
<thead>
  <tr>
    <th scope="col">Title</th>
  </tr>
</thead>
<tbody>
    {% for task in tasks %}
      {% if task.finished == False %}
        <tr>
          <td>{{task.title}}</td>
          <td>
            <form method="post">
              {% csrf_token %}
              <button type="submit"  name= "task_id_update" value="{{task.id}}">Mark as finished</button>
            </form>
          </td>
          <td>
            <form method="post">
              {% csrf_token %}
              <button type="submit"  name= "task_id_delete" value="{{task.id}}">Delete</button>
            </form>
          </td>
        </tr>
        {% else %}
        <tr >
          <td>{{task.title}}</td>
          <td>
            <form method="post">
              {% csrf_token %}
              <button type="submit"  name= "task_id_delete" value="{{task.id}}">Delete</button>
            </form>
          </td>
        </tr>
      {% endif %}
    {% empty %}
      No tasks!
    {% endfor %}
</tbody>
</table>

Is there any better way to do this?

Thanks a lot!

CodePudding user response:

The order of tasks, during iteration in the for loop, if not explicitly set via an order_by QuerySet method, will be determined by the ordering Model Meta option. If neither is set, then you'll get the ordering of the values in the database storage. Most databases will just put the last updated record somewhere where it's convenient - at the beginning or the end of the table, for example.

So, you really have several options, but these two stand out:

  1. Add ordering to your Task model's Meta class
  2. Add order_by("FIELD_NAME_HERE", ) to your query, before the .all(), on line #2
  • Related