3

I'm quite new in the development with django and I hope someone can help me. I have two main models in one view and in one template. Each one of my "main" models has its own "sub" model (with a foreign key). My output is fine and it works so far.

My problem is, I would like to sort the sub model of my second main model by name. Is this possible, or what do I need to change this?

In my example, I want to sort 'occupant.last_name' by name.

I have a picture what it looks like right now: occupant.last_name

My models.py

class Management[...]
class Employee[...]

class Houses(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Occupant(models.Model):
    house = models.ForeignKey(Houses, on_delete=models.CASCADE)
    last_name = models.CharField(max_length=50)
    first_name = models.CharField(max_length=50)
    room = models.IntegerField(default=0)

    def __str__(self):
        return self.first_name

My views.py

class IndexView(ListView):
    context_object_name = 'all_management_list'
    template_name = 'blackboard/index.html'
    queryset = Management.objects.order_by('order_number')

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['Houses'] = Houses.objects.all()
        # And so on for more models
        return context

My template.html

{% for houses in Houses %}
<h3>{{ houses.name }}</h3>
<table><tbody>
    {% for occupant in houses.occupant_set.all %}
    <tr>
        <td>{{ occupant.last_name }}, {{ occupant.first_name }}</td>
        <td>{{ occupant.room }}</td>
    </tr>
[...]

Thank you so much for helping and sorry for my bad english. :)

With best regards

borsTiHD

borsTiHD
  • 253
  • 3
  • 17

1 Answers1

8

You can sort in queryset by order_by()

order make the default order in model by last_name by adding this under class Meta

class Occupant(models.Model):
    house = models.ForeignKey(Houses, on_delete=models.CASCADE)
    last_name = models.CharField(max_length=50)
    first_name = models.CharField(max_length=50)
    room = models.IntegerField(default=0)

    def __str__(self):
       return self.first_name
    class Meta:
       ordering = ('last_name',)
Ahmed Elemam
  • 396
  • 3
  • 12