django使用管理器来获取自定义查询集

时间:2014-04-29 17:06:27

标签: django django-queryset

我正在尝试获取一个随机的对象列表,并将其用作表单字段的查询集。但由于它是一个列表而不是查询集,因此无法工作。一位朋友建议使用经理。但现在我不太清楚从哪里开始。

我的功能是获取" queryset"列表:

def get_job_list():
    all_jobs = ShortJob.objects.exclude(rarity__exact=0)
    always = ShortJob.objects.filter(rarity=0)
    pick_list = []
    job_list = []

    for job in all_jobs:
        pick_list.extend([job] * job.rarity)

    counter = 0
    while counter < 5:
        counter += 1
        job = choice(pick_list)
        job_list.append(job)

        while job in pick_list:
            pick_list.remove(job)

    for job in always:
        job_list.append(job)

    return job_list

和我的表格:

class ShortJobForm(forms.Form):

    options = forms.ModelChoiceField(queryset=ShortJob.get_job_list, widget=forms.RadioSelect)

有人可以指出我正确的方向来解决这个问题

到目前为止,我尝试将该功能重写为经理:

class ShortJobManager(models.Manager):
""" create a random short job queryset"""

    def get_queryset(self):
        all_jobs = ShortJob.objects.exclude(rarity__exact=0)
        always = ShortJob.objects.filter(rarity=0)
        pick_list = []
        job_list = []

        for job in all_jobs:
            pick_list.extend([job] * job.rarity)

        counter = 0
        while counter < 5:
            counter += 1
            job = choice(pick_list)
            job_list.append(job)

            while job in pick_list:
                pick_list.remove(job)

        for job in always:
            job_list.append(job)

        return super(ShortJobManager, self).get_queryset(job_list)

2 个答案:

答案 0 :(得分:1)

您可以像这样更改get_job_list()函数,以便它返回一个查询集:

def get_job_list():
    all_jobs = ShortJob.objects.exclude(rarity__exact=0)
    always = ShortJob.objects.filter(rarity=0)
    pick_list = []
    pk_list = []

    for job in all_jobs:
        pick_list.extend([job.pk] * job.rarity)  # list of pks

    counter = 0
    while counter < 5:
        counter += 1
        job_pk = choice(pick_list)
        pk_list.append(job_pk)

        while job_pk in pick_list:
            pick_list.remove(job_pk)

    # pk_list is now a list of pks you can filter on
    return always.filter(pk__in=pk_list)

大致相似的东西。我试图保持你的功能的目的,但可能在某些地方误解了它。要点是:

您可以选择随机pks,然后对其进行过滤以获取查询集。

答案 1 :(得分:0)

我建议您使用raw qs包含UNION部分。像这样:

 ShortJob.objects.raw('SELECT * FROM myapp_shortjob WHERE rarity=0 UNION SELECT * FROM myapp_shortjob WHERE rarity!=0 ORDER BY random()')