【问题标题】:get distinct and random queryset in django在 django 中获取不同且随机的查询集
【发布时间】:2014-08-12 17:15:35
【问题描述】:

您好,我正在尝试做一个可以替换此查询的查询集:

SELECT DISTINCT ON (question.exercise_id) question.exercise_id, question.* 
    FROM 
        exercise, question 
    WHERE exercise.id = question.exercise_id
    OFFSET random()*(SELECT count(*) FROM question) LIMIT 5;

之前的查询工作正常,

我尝试在 django 中使用

random_questions = Questions.objects.filter(
    text=text # text is a Text instance
).distinct('text').order_by('?')[:5]

但不起作用,我搜索并发现我如何使它永远不会起作用,但我没有找到替代解决方案

谢谢

【问题讨论】:

  • 有区别吗?或在提供问题时拼写错误?如果是,请将其更改为不同的。

标签: django postgresql django-queryset


【解决方案1】:

我没有找到一个答案,所以我能找到的唯一一种方法是:

texts = Text.objects.all().order_by('?') # add .prefetch_related('questions_text') or .select_related('questions_text') could help to do the query faster
questions = []
for text in texts:
    questions.append(
        Question.objects.filter(
            text=text
        ).order_by('?')[0]
    )

【讨论】:

    【解决方案2】:

    试试这样的:

    random_questions = Questions.objects.filter(
        text=text # text is a Text instance
    ).distinct('text').order_by('text', '?')
    

    然后使用 len(random_questions) 从该查询集中随机选择五个项目以查看有多少结果。将比您目前正在做的更快。

    您也可以使用原始 sql 执行此操作(但验证您的用户输入,如果有的话):

    https://docs.djangoproject.com/en/1.10/topics/db/sql/#executing-custom-sql-directly

    【讨论】:

      猜你喜欢
      • 2020-06-03
      • 2011-09-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 2015-01-28
      • 2021-12-10
      • 2014-01-25
      • 1970-01-01
      相关资源
      最近更新 更多