通过annotate从字典列表return中获取name键的值,然后按name排序?
Get the value of name key from the list of dictionaries return by the annotate and then sort by name?
我的代码
def get_areas(self, obj):
text = []
if obj.areas and not obj.areas == []:
print(json.loads(obj.area_count))
print(type(obj.area_count))
return json.loads(obj.area_count)
return "-"
get_areas.short_description = "Areas"
get_areas.admin_order_field= "area_count"
def get_queryset(self, request):
from django.contrib.postgres.fields.jsonb import KeyTextTransform
qs = super(UserAdmin, self).get_queryset(request)
filtered_query = qs.filter(
is_superuser=False, is_staff=False
).annotate(
wishlist_count=Count('wishlist', distinct=True),
booking_count=Count('booking', distinct=True),
review_count=Count('review', distinct=True),
suggestion_count=Count('suggestion', distinct=True),
home_city=NullIf('home__city'),
home_country=NullIf('home__country'),
area_count = F('areas'),
)
我得到的是一个 str 类型的列表,类似于:
"[{'id': 98, 'name': 'Khalifa City and Masdar City', 'city': 'Abu Dhabi'},
{'id': 99, 'name': 'Masdar City', 'city': 'Abu Dhabi'}]"
<class 'str'>
我想要的是姓名列表:
['Khalifa City and Masdar City','Madsar City']
那么,如何将 return area_count = F('areas')
的结果作为 list 而不是 str
注意:该列表可以包含超过 1 个词典,我想 return 只是 names.Any 的努力将不胜感激
您需要 F("areas")
的 annotate
做什么?
只需删除它并访问 "areas" 作为 QS 中对象的属性。
我的代码
def get_areas(self, obj):
text = []
if obj.areas and not obj.areas == []:
print(json.loads(obj.area_count))
print(type(obj.area_count))
return json.loads(obj.area_count)
return "-"
get_areas.short_description = "Areas"
get_areas.admin_order_field= "area_count"
def get_queryset(self, request):
from django.contrib.postgres.fields.jsonb import KeyTextTransform
qs = super(UserAdmin, self).get_queryset(request)
filtered_query = qs.filter(
is_superuser=False, is_staff=False
).annotate(
wishlist_count=Count('wishlist', distinct=True),
booking_count=Count('booking', distinct=True),
review_count=Count('review', distinct=True),
suggestion_count=Count('suggestion', distinct=True),
home_city=NullIf('home__city'),
home_country=NullIf('home__country'),
area_count = F('areas'),
)
我得到的是一个 str 类型的列表,类似于:
"[{'id': 98, 'name': 'Khalifa City and Masdar City', 'city': 'Abu Dhabi'},
{'id': 99, 'name': 'Masdar City', 'city': 'Abu Dhabi'}]"
<class 'str'>
我想要的是姓名列表:
['Khalifa City and Masdar City','Madsar City']
那么,如何将 return area_count = F('areas')
的结果作为 list 而不是 str
注意:该列表可以包含超过 1 个词典,我想 return 只是 names.Any 的努力将不胜感激
您需要 F("areas")
的 annotate
做什么?
只需删除它并访问 "areas" 作为 QS 中对象的属性。