【问题标题】:Django/Python Chain and Sort QuerysetsDjango/Python 链式和排序查询集
【发布时间】:2014-12-01 16:41:57
【问题描述】:

我有一个包含 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 = ???

我的模型是:

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 排序的数组中所有inventoryDe​​tails 中计算的所有项目的列表,并且不重复

我被困在这里,我不知道链是否正确,排序功能给我一个错误,说该项目没有'epc'属性。

请帮忙!

【问题讨论】:

  • 请问您可以添加您的模型吗?

标签: python django


【解决方案1】:

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

但是您可以使用InventoryDetails.objects.filter(inventory_location__in=inv_locations).order_by('epc').distinct() 为自己省去一些麻烦 - 这将在数据库中进行排序和唯一化,而不是在您的视图中进行。

【讨论】:

  • distinct() 中的空参数会使所有字段唯一吗?还是我应该放一个像 .distinct('epc') 这样的字段?
  • 查看文档以获得完整的详细信息:docs.djangoproject.com/en/dev/ref/models/querysets/… 短版,它使所有字段唯一——每个底层数据库行将仅返回一次。您可能在这里不需要它,如果您只需要每个epc 一次,您可能需要在 Python 中完成该部分。仅在 PostgreSQL 上,您可以使用 .distinct('epc')
猜你喜欢
  • 1970-01-01
  • 2021-05-05
  • 2012-07-30
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 2020-08-16
  • 2013-09-26
  • 1970-01-01
相关资源
最近更新 更多