如何将Django应用的URL字符串添加到数据库并随机选择?

困境

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

这在我的本地计算机上运行良好,但是自从我发现多线程处理并使用如下所示的常量列表后,SURVEY_URLS在将项目上载到服务器时就引起了问题。我想改为将其存储在我的数据库中。

问题)

  • 如何SURVEY_URLS在MySQL数据库中添加/存储以下字符串列表?
  • 如何从同一数据库中删除特定的URL字符串?(如下)

以下是我现有的代码,它具有我需要的所有功能,并且可以在我的机器上正常工作。与多个并发用户打交道时,我只需要使其正常工作即可。

谢谢

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并将其附加到您的网址中

不确定这种方法的有效性如何,但是应该可行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将每个单词或获取字符串作为单独的条目添加到数据库

如何将当前查询字符串添加到Django模板中的URL?

如何将数据参数添加到HTML字符串并返回字符串?

javascript将文本添加到发送到数据库的字符串

Android Studio:将单选按钮字符串添加到数据库

将数据库中存储的JSON添加到JSON字符串

如何将新数据从ebay添加到Django中的数据库?

连接字符串将数据库添加到sql中,而不是从数据库中读取

如何遍历字符串数组并添加到领域数据库?

如果 url 不包含子字符串,如何将路径添加到 url

如何将信息添加到字符串

如何将字符串添加到数组?

如何将条形图添加到基于Django的数据库中?

如何将NullableBooleanField添加到现有的Django数据库中?

如何将数据库路由器添加到Django项目

如何将包含特定字符串的URL添加到数组中?

Node.js + express 如何将字符串添加到请求 url 中?

如何将字符串添加到查询Django

我如何将数字和字符串添加到我的 Django

如何将动态数据(如字符串数组)添加到微调器

如何将数据从表添加到字符串

如何将数据添加到我的Android应用程序中的现有数据库?

将具有特定字符串格式的日期时间添加到SQLite数据库

实体框架是否可以在将实体添加到数据库时生成字符串模式值?

如何将Integer添加到字符串并获得字符串答案?

如何将字符串数组的元素添加到字符串数组列表?

如何将子字符串添加到字符串中

如何将字符串添加到数组并返回字符串

如何将字符串(单词)添加到字符串[]数组?Java,输入