我试图获得一个对象的随机列表,并将其用作表单字段的查询集。但由于它是一个列表而不是查询集,所以这是行不通的。一位朋友建议找一位经理来做这件事。但现在我不太确定从哪里开始。
我获取"查询集"列表的函数:
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)
您可以这样更改get_job_list((函数,使其返回一个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)
大致是这样的。我试图保持你的功能的目的,但可能在某些地方误解了它。要点是:
您可以选择随机pk,然后对其进行筛选,以获得查询集
我建议您可以使用原始qs包含UNION部分。类似这样的东西:
ShortJob.objects.raw('SELECT * FROM myapp_shortjob WHERE rarity=0 UNION SELECT * FROM myapp_shortjob WHERE rarity!=0 ORDER BY random()')