[Answer]-Django use a manager to get a custom queryset

1๐Ÿ‘

โœ…

You can change your get_job_list() function like so, so that it returns a queryset:

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)

Something roughly like that. I tried to maintain the purpose of your function, but may have misunderstood it in some places. Main point being:

You can pick random pks and then filter on them in order to get a queryset.

๐Ÿ‘คpcoronel

0๐Ÿ‘

I suggest you may use raw qs contains UNION section. Something like this:

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

Leave a comment