You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django的views.py中列出所有django-waffle开关?

在Django的views.py中列出所有django-waffle开关的方法

要在views.py中获取所有django-waffle的Switch实例,直接操作其内置的Switch模型即可,步骤如下:

  1. 导入Switch模型
    首先从django-waffle的models模块中导入Switch类:

    from waffle.models import Switch
    
  2. 查询所有开关
    在视图函数/类中,通过Django ORM的all()方法获取所有开关实例,你可以根据需求整理数据格式:

示例1:函数视图(传递到模板渲染)

from django.shortcuts import render
from waffle.models import Switch

def list_switches(request):
    # 获取所有开关对象
    all_switches = Switch.objects.all()
    # 整理成便于模板使用的字典列表
    switch_data = [
        {
            "name": switch.name,
            "is_active": switch.active,
            "created_at": switch.created.strftime("%Y-%m-%d %H:%M"),
            "updated_at": switch.modified.strftime("%Y-%m-%d %H:%M")
        }
        for switch in all_switches
    ]
    return render(request, "switches/list.html", {"switches": switch_data})

示例2:API视图(返回JSON格式)

如果需要通过接口返回开关列表,可以用Django REST Framework实现:

from rest_framework.views import APIView
from rest_framework.response import Response
from waffle.models import Switch

class SwitchListAPI(APIView):
    def get(self, request):
        # 直接提取需要的字段返回
        switch_list = Switch.objects.values("name", "active", "created", "modified")
        return Response({"switches": list(switch_list)})

说明

django-waffle的Switch模型默认包含以下核心字段:

  • name:开关的唯一标识(与管理面板中定义的一致)
  • active:布尔值,标识开关是否启用
  • created:开关创建时间
  • modified:开关最后修改时间

你可以根据业务需求筛选或扩展这些字段的使用。

内容的提问来源于stack exchange,提问作者Waleed Farrukh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:25:30