Django/Python链和排序查询集

2024-04-25 14:41:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个库存盘点,有N个位置,这个位置需要计数N次,所以我有一个模型用于“位置标题”,另一个模型用于每个标题的项目列表。

我需要对N个查询集中的项进行链、排序和获得唯一的结果

我有这个:

loc_id = request.POST['loc_id'] # the Id of my location pivot
inv_location = InventoryLocations.objects.get(pk=loc_id) # get the location count pivot
inv_locations = InventoryLocations.objects.filter(location=inv_location.location,
                inventory=inv_location.inventory) #get all related locations counts

# At this point i can have N inv_locations

count_items = [] # list of items in all inventory counts 
for l in inv_locations:
    items = InventoryDetails.objects.filter(inventory_location = l) # get items of every count 
    count_items.append(items)

# Now I have all the items counted in the counts_items array, I need to get from this a single
# list of items Ordered and not repeated    

all_items = chain(count_items) <<< IS THIS CORRECT??
sorted_items = sorted(all_items,key=lambda item: item.epc) << THIS GIVE ME ERROR
unique_items = ???

我的模型是:

^{pr2}$

基本上,我需要一个按epc排序且不重复的数组中所有inventoryDetails中计数的所有项目的列表

我被困在这里,我不知道链是否做得对,而sort函数给我一个错误,告诉我该项没有'epc'属性。

救命啊!


Tags: ofthe模型idgetobjectscountitems
1条回答
网友
1楼 · 发布于 2024-04-25 14:41:17

为了解决眼前的问题-假设是itertools.chainchain需要多个iterable。使用chain(*count_items)展开查询集列表。在

但是,使用InventoryDetails.objects.filter(inventory_location__in=inv_locations).order_by('epc').distinct()-这将在数据库中进行排序和uniquing,而不是在视图中执行。在

相关问题 更多 >