Django在模型中对List进行排序

时间:2022-08-29 20:22:30

I want to keep a list of addresses sorted inside a table.

我想保留一个在表格中排序的地址列表。

Here is the code for my sorting: (it doesn't work and honestly I have no idea how to go about this I'm new to Django/Python)

这是我的排序代码:(它不起作用,老实说,我不知道如何解决这个问题我是Django / Python的新手)

def detail(request, table_name):
    table = get_object_or_404(Table, name=table_name)
    addressSet = table.address_set.all();
    addressSet.sort(key=operator.attrgetter('address'))

Here is the models.py for these 2 items:

以下是这两个项目的models.py:

class Table(models.Model):
    name = models.CharField(max_length = 100)
    description = models.CharField(max_length = 100)
    size = models.IntegerField()
    def __str__(self):
        return self.name + " - " + self.description
class Address(models.Model):
    address = models.CharField(max_length = 20)
    description = models.CharField(max_length = 100)
    table = models.ForeignKey(Table)
    def __str__(self):
        return str(self.address) 

1 个解决方案

#1


1  

You can set the ordering and many other options for a model through the use of the meta class. So for your example:

您可以通过使用元类为模型设置排序和许多其他选项。所以对你的例子:

class Address(models.Model):
    address = models.CharField(max_length=20)
    ...

    class Meta:
        ordering = ['address']

This will order Address models in your queryset after they have been queried from the database. This will have no impact on how the data is underlying stored.

这将在从数据库查询后在查询集中对Address模型进行排序。这对数据的底层存储方式没有影响。

#1


1  

You can set the ordering and many other options for a model through the use of the meta class. So for your example:

您可以通过使用元类为模型设置排序和许多其他选项。所以对你的例子:

class Address(models.Model):
    address = models.CharField(max_length=20)
    ...

    class Meta:
        ordering = ['address']

This will order Address models in your queryset after they have been queried from the database. This will have no impact on how the data is underlying stored.

这将在从数据库查询后在查询集中对Address模型进行排序。这对数据的底层存储方式没有影响。