2014-12-01 56 views
0

我有一個有N個位置的庫存盤點,這個位置需要計數N次,所以我有一個模型用於「位置標題」,另一個用於每個標題的項目列表。Django/Python鏈和排序查詢集

我需要連鎖,排序和獲得的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 = ??? 

我的車型有:

class InventoryCount(models.Model): 
    ...nothing important 

class InventoryLocation(models.Model): 
    inventory= models.ForeignKey(InventoryCount) 
    location= models.ForeignKey(Location) 
    ... 

class InventoryDetails(models.Model): 
    inventory_location= models.ForeignKey(InventoryLocations) 
    epc = models.CharField(max_length=25, null=True, blank=True) 
    item= models.ForeignKey(Item) 
    ... 

基本上,我需要所有物品清單中的所有物品清單數量按epc排序,並且不重複

我被困在這裏,我不知道鏈是否正確,排序功能給我一個錯誤,說該項目沒有'epc'屬性。

幫助PLZ!

+0

你可以添加你的模型plz? – cdvv7788 2014-12-01 16:56:58

回答

1

要解決您的直接問題 - 假設itertools.chain,chain需要多個迭代。使用chain(*count_items)來擴展您的查詢集列表。

但是你可以通過使用InventoryDetails.objects.filter(inventory_location__in=inv_locations).order_by('epc').distinct()來節省自己的一些麻煩 - 它會在數據庫中進行排序和排序,而不是在視圖中進行排序和排序。

+0

在distinct()中的空參數將唯一的所有字段?或者我應該把一個像.distinct('epc')這樣的字段? – 2014-12-01 17:10:32

+0

請參閱文檔以獲取完整詳細信息:https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct簡短版本,它不區分所有字段 - 每個基礎數據庫行將只返回一次。你可能不需要它,如果你想每個'epc'只有一次,你可能需要在Python中完成這部分。僅在PostgreSQL上,您可以使用'.distinct('epc')'。 – 2014-12-01 17:52:05