我可以按HStoreField内的值对QuerySet的结果进行排序吗,例如,我有一个模型:
class Product(model.Models):
name = CharField(max_length=100)
properties = HStoreField()
我想把我产品的一些特性存储在HStoreField中,比如:
{ 'discount': '10', 'color': 'white'}
鉴于此,我想按折扣订购结果查询集。
最佳答案
上面的答案不起作用。从未为HStoreField
实现过顺序转换,请参见https://code.djangoproject.com/ticket/24747。
但是,https://code.djangoproject.com/ticket/24592中的建议是有效的。这里有更多的细节。
from django.contrib.gis.db.models import TextField, HStoreField, Model
from django.db.models import F, Func, Value
class MyThing(Model):
name: TextField()
keys: HStoreField()
things = [MyThing(name='foo'),
MyThing(name='bar'),
MyThing(name='baz')]
things[0].keys['movie'] = 'Jaws'
things[1].keys['movie'] = 'Psycho'
things[2].keys['movie'] = 'The Birds'
things[0].keys['rating'] = 5
things[1].keys['rating'] = 4
things[2].keys['year'] = '1963'
# Informal search
MyThing.objects\
.filter(keys__has_key='rating')\
.order_by(Func(F('keys'), Value('movie'),
function='',
arg_joiner=' -> ',
output_field=TextField()))
形式化搜索与上面第二个链接中描述的完全相同。将上述代码片段中的导入与该代码一起使用。
关于django - Django postgres HStoreField命令由,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30774845/