如何将 Django 应用程序的 URL 字符串随机添加到数据库中 select?

How to add URL strings for a Django app to a database and randomly select?

我构建了一个小型调查应用程序,通过随机选择 URL 的最后一部分并将其附加到按钮 link 上,将参与者随机分配到 9 条路径之一。然后我使用例如{% if 'surveyone' in request.path %} 等在我的模板标签中向用户显示正确的内容。

这在我的本地机器上运行良好,但后来我发现多线程处理和使用如下常量列表 SURVEY_URLS 在将项目上传到服务器时会导致问题。我想改为将其存储在我的数据库中。

问题

下面是我现有的代码,它具有我需要的所有功能并且在我的机器上运行良好。在处理多个并发用户时,我只需要让它正常工作。

谢谢

views.py

SURVEY_URLS = ['/surveyone/', '/surveytwo/', '/surveythree/', '/surveyfour/', '/surveyfive/', '/surveysix/', '/surveyseven/', '/surveyeight/', '/surveynine/']

def begin(request):

    total_path_counter = TotalCounter.objects.get_or_create(total_max_counter__gte=0)[0]  
    if total_path_counter.total_max_counter < 100:

        survey_url = random.choice(SURVEY_URLS)

        if survey_url == '/surveyone/':    
            survey_path_counter = SurveyCounter.objects.get_or_create(survey_wizard_type = 'survey_wizard_one')[0]

            if survey_path_counter.survey_wizard_count > 9: 
                SURVEY_URLS.remove('/surveyone/')

        elif survey_url == '/surveytwo/':    
            survey_path_counter = SurveyCounter.objects.get_or_create(survey_wizard_type = 'survey_wizard_two')[0]

            if survey_path_counter.survey_wizard_count > 9: 
                SURVEY_URLS.remove('/surveytwo/')

        ....
        ....


        elif survey_url == '/surveynine/':
            survey_path_counter = SurveyCounter.objects.get_or_create(survey_wizard_type = 'survey_wizard_nine')[0]

            if survey_path_counter.survey_wizard_count > 9:
                SURVEY_URLS.remove('/surveynine/')

        return render(request, 'Begin.html', {'survey_url': survey_url})    
    else:
        return render(request, 'surveyfull.html')

Begin.html

<a class="btn btn-success" href="/experiment{{survey_url}}">Begin Instruction Tasks</a>

嗯,我想你可以制作一个像这样的新模型:

class Survey(model.Model):
  name = models.Charfield(max_length=50) # surveyone goes here
  ...

在视图中你可以像这样拉随机:

survey_count = Survey.objects.all().count()
random_survey_index = random.randint(0, survey_count - 1)

通过 random_survey_index 获取实例名称并将其附加到您的 url

不确定这种方法的效果如何,但应该有效。