[英]How to order Django Tables2 column by model property that depends on outside model query
Say I have two models, one with a property: 假设我有两种模型,一种具有属性:
class Name(models.Model):
name = models.CharField()
class Name_ID(models.Model):
name_id = models.IntegerField()
@property
def object_name(self):
try:
return Name.objects.get(id=self.name_id)
except Name.DoesNotExist:
return ''
Then I try making a table using django-tables2 for the Name_ID model only: 然后,我尝试仅使用Name_ID模型的django-tables2来创建表:
class NameIDTable(tables.Table):
object_name = tables.Column()
class Meta:
model = Name_ID
row_attrs = {'data-id': lambda record: record.pk}
exclude = ('name_id',)
attrs = {'class': 'table table-striped', 'style': 'display: block; overflow: auto;'}
The table successfully shows the object_name column with all of the values from the property. 该表成功显示了object_name列以及该属性中的所有值。 However, when I try clicking on the column header for it so I can order them by name, I get an error because 'object_name' is not an actual field in the Name_ID model.
但是,当我尝试单击列标题以便按名称对其进行排序时,由于“ object_name”不是Name_ID模型中的实际字段,因此会出现错误。 Many of the solutions I found don't work because they assume that you're using fields from the model itself, not queries from outside models.
我发现的许多解决方案都行不通,因为它们假定您使用的是模型本身的字段,而不是外部模型的查询。 How do you make the table orderable by the object_name property?
如何通过object_name属性使表可排序?
The documentation has a page on this: custom ordering . 文档上有一个页面: 自定义订购 。
That said, you should tell django-tables2 how to order the query, that's not something django-tables2 can do for you, as the implementation of your property is opaque to django-tables2. 就是说,您应该告诉django-tables2如何排序查询,这不是django-tables2可以为您做的事情,因为属性的实现对于django-tables2是不透明的。 In your example, things would be easier if the
name_id
column were a models.ForeignKey
, and not models.IntegerField()
, but I assume you have a reason to do so. 在您的示例中,如果
name_id
列是models.ForeignKey
,而不是models.IntegerField()
,事情会更容易些,但是我想您有这样做的理由。
If you know how to sort the query, you can write an order_object_name
method, like explained in the docs. 如果您知道如何对查询进行排序,则可以编写一个
order_object_name
方法,如文档中所述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.