简体   繁体   English

从其他字段派生的Django可排序字段

[英]Django sortable field derived from other fields

Edited with own answer: original question below. 编辑有自己的答案:以下是原始问题。

In here it recommends a few approaches, and the simplest one to me is to just add an extra field but override save to update it, then I get standard functionality for free. 这里,它推荐了一些方法,而对我来说,最简单的方法是仅添加一个额外的字段,但覆盖保存以对其进行更新,然后我免费获得标准功能。 So my app is now: 所以我的应用现在是:

#views.py
highest_p2w = Car.objects.filter().order_by('-p2w')[0]
lowest_p2w = Car.objects.filter().order_by('p2w')[0]

.

#models.py
p2w = models.FloatField("Power to weight ratio",editable=False)

def save(self, *args, **kwargs):
    self.p2w = (float(self.bhp) * 1000 ) / float(self.weight)
    super(Car, self).save(*args, **kwargs)

The only disadvantage is that I had to do a save() on any existing records to update the value. 唯一的缺点是我必须对任何现有记录执行save()来更新值。 But any new records enter the value at save() time. 但是任何新记录都会在save()时输入值。


Original Question 原始问题

I'd like to have a dynamic value which is calculated from 2 fields returned in Django from the model. 我想有一个动态值,该值是根据模型中Django返回的2个字段计算得出的。

I think I can do this with a method, but I need to be able to sort on it just like the other fields. 我想我可以用一种方法来做到这一点,但是我需要能够像其他领域一样对它进行排序。

#Models.py:
class Car(models.Model):
    weight = models.IntegerField("Weight in KG")
    bhp = models.IntegerField("BHP")

I'd like to have a field called power_to_weight_ratio that just calculates ( self.bhp * 1000 ) / self.weight 我想要一个名为power_to_weight_ratio的字段,该字段仅计算(self.bhp * 1000)/ self.weight

As this is a dynamic value, it doesn't need to be stored. 由于这是一个动态值,因此不需要存储。 BUT it does need to be sortable, as I sorted on all the other fields in the model. 但是它确实需要是可排序的,就像我在模型中的所有其他字段上排序一样。

I'd think I could just do something like 我想我可以做些类似的事情

power_to_weight = ( self.bhp * 1000 ) / self.weight

but I assume I need to start overriding methods to give me the ability to sort. 但我认为我需要开始重写方法才能赋予我排序的能力。 Django docs don't seem to mention this in the model custom field documentation. Django文档似乎在模型自定义字段文档中没有提及这一点。

Thanks. 谢谢。

I am so glad that I've done it! 我很高兴自己做到了! ^_^ free to enjoy it ^ _ ^免费享受

I've tried the following that is most similar to satisfy your need (tested sqlite3 database) 我尝试了以下最满足您需求的内容(经过测试的sqlite3数据库)

admin.py admin.py

from django.contrib import admin
from .models import Car

class CarAdmin(admin.ModelAdmin):
    list_display = ('weight','bhp','power_to_weight2',)

    def queryset(self,request):
        return super(CarAdmin,self).queryset(request).extra(select={'ptw':'(CAST((bhp) AS FLOAT))/weight'})

    def power_to_weight2(self,obj):
        return obj.bhp*1000/float(obj.weight)#python 2.x,float not need in python3.x
    power_to_weight2.short_description = 'power_to_weight'
    power_to_weight2.admin_order_field = 'ptw'

admin.site.register(Car,CarAdmin)
  1. about model.objects.extra() see: https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra 有关model.objects.extra()请参见: https : model.objects.extra()

  2. When query database, / means you are doing integer division so use CAST AS FLOAT to convert it to float,detail see here: What is wrong with this SQL Server query division calculation? 查询数据库时,/表示您正在执行整数除法,因此请使用CAST AS FLOAT将其转换为float,详细信息请参见: SQL Server查询除法计算有什么问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM