我可以简化我的 django 数据库吗?我有许多不同模型的相似视图(即创建、列表)

Can I simplify my django database where I have many similar views (i.e. create, list) for many different models

我有几个具有相似视图的模型...有没有办法编写一个 list/create/detail 视图并将该单一视图应用于我的所有模型?

def modelalist(request):
    objects = ModelA.objects.all()
    context = {
        "objects": objects,
    }
    return render(request, "app/modelalist.html", context)

def modelblist(request):
    objects = ModelB.objects.all()
    context = {
        "objects": objects,
    }
    return render(request, "app/modelblist.html", context)

# and on and on....

此处的最佳做法是什么?

根据您的示例,我假设您可以执行以下操作:

def list_model(request, model_class, template, **kwargs):
  objects = model_class.object.all(**kwargs)
  context = {
      "objects": objects,
  }
  return render(request, template, context)

然后为您的其他模型调用它:

def modelalist(request):
  return list_model(request, ModelA, "app/modelalist.html")

def modelblist(request):
  return list_model(request, ModelB, "app/modelblist.html")

如果您的所有模板都在一个标准位置,您也可以重构它。

您可以考虑使用 class-based views. If you use the built-in class-based views ListView 几乎没有代码重复。

from django.views.generic.list import ListView

class ModelAList(ListView):
    model = ModelA
    template_name = 'app/modelblist.html'


class ModelBList(ListView):
    model = ModelB
    template_name = 'app/modelblist.html'
如果您使用默认值 "[app_name]/[model_name]_list.html"

template_name 是可选的。这也需要您重写您的网址:

urlpatterns = [
    url('...', modelalist, name='...'),           # old
    url('...', ModelAList.as_view(), name='...')  # new
]

最后一个区别是模板中的上下文变量 objects 现在是 object_list

手工解决方案:

# views.py 
import os
from django.apps import apps

def modellist(request, app_label model_name):
    model = apps.get_model(app_label, model_name)
    objects = model.objects.all()
    template = os.path.join(app_label, "{}list.html".format(model_name)
    context = {
        "objects":objects,
        }
    return render(request, template, context)

# urls.py
   urlpatterns = [
       url(r"^(?P<app_label>\w+)/(?P<model_name)\w+/", views.modellist, name="modellist")
   ]

但我绝对不会做这样的事