Reputation: 3040
I have an inventory count that has N locations, this locations needs to be counted N times, so I have one model for "the location header" and another for the item list of every header.
I need to chain,sort AND get unique results of the items in N querysets
I have this:
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 = ???
My models are:
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)
...
Basically, I need a list of all items counted in all inventoryDetails in the array sorted by epc
and not repeated
I'm stuck in here, i dont know if the chain is doing it right and the sort function gives me an error saying that the item has no 'epc' attribute.
Help plz!
Upvotes: 0
Views: 1220
Reputation: 37319
To solve your immediate problem - assuming that's itertools.chain
, chain
takes multiple iterables. Use chain(*count_items)
to expand your list of querysets.
But you can save yourself some trouble by using InventoryDetails.objects.filter(inventory_location__in=inv_locations).order_by('epc').distinct()
- that'll do the sorting and uniquing in the database rather than you doing it in your view.
Upvotes: 1