【问题标题】:Django: Picking from QuerySet without slicing itDjango:从 QuerySet 中挑选而不切片
【发布时间】:2021-05-23 20:27:50
【问题描述】:

我在 Django 中有以下基本模型:

class Group(models.Model):

class People(models.Model):
    groups = models.ManyToManyField(Group, related_name='members')

class Cars(models.Model):
    groups = models.ManyToManyField(Group, related_name='vehicles')

我想从某些组中选择一定数量的人和汽车。我保存在列表中的组和相应的比例:

groups = [ some groups ]
proportion_pps = [ some positive integer list ]
proportion_cars = [ some positive integer list ]

现在我选择的代码如下所示:

for x, group in enumerate(groups):

pps |= People.objects.filter(groups=grop).all().order_by('?')#[:proportion_pps[x - 1]]
crs |= Cars.objects.filter(groups=group).all().order_by('?')#[:proportion_crs[x - 1]]

到目前为止一切都很好......但是现在我在尝试时遇到了“切片”错误:

pps.distinct()
crs.distinct()

或类似的东西:

list_pps = list(pps.values_list('id', flat=True).order_by('?'))

我看不出有什么办法。任何帮助将不胜感激...谢谢!

【问题讨论】:

  • #[:proportion_pps[x - 1]] 应该做什么?
  • 我忘了删除评论标签 (#),以防您是这个意思。否则,比如[:7],我只想随机选择该组中的 7 个元素。

标签: django filtering django-queryset slice


【解决方案1】:

根据使用的数据库,您可以使用.union(…) [Django-doc]

people = People.objects.none().union(*[
    People.objects.filter(groups=group).all().order_by('?')[:n]
    for group, n in zip(groups, proportion_pps)
])

【讨论】:

  • 我在生产中使用 Postgres,现在正在开发中使用 djangos sqlite3。你的建议到目前为止有效,但现在我遇到了麻烦:list_pps = list(pps.values_list('id', flat=True).order_by('?')),上面写着LIMIT/OFFSET not allowed in subqueries of compound statements.
  • @zeus:在联合之后排序会很棘手。但是,如果您使用list,则无论如何都没有必要,因为那时您可以简单地在 Python/Django 级别进行随机播放。
  • 谢谢。但是 list_id 的东西在没有排序的情况下也不起作用:list_pps = list(pps.values_list('id', flat=True)) 遇到同样的错误
  • @zeus: from random import data; data = [p.pk for p in pps]; shuffle(data)
  • 我做了import random 因为from random import data 给了我一个错误(Cannot find reference 'data' in 'random.pyi')。然后你的建议 data= 命令被执行,但我遇到了与以前相同的限制/偏移错误。
猜你喜欢
  • 2016-01-02
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多