在django中获取不同的随机查询集

时间:2014-08-12 17:15:36

标签: django postgresql django-queryset

您好我正在尝试执行可以替换此查询的查询集:

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]

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

感谢

2 个答案:

答案 0 :(得分: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]
    )

答案 1 :(得分:0)

尝试这样的事情:

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