问题描述
在我的 Django 项目中,我发现我的 Web 模板视图和 DRF 视图的 get
方法的逻辑非常相似。但是,generic.ListView
和 ObjectMultipleModelAPIView
在层次结构中共享祖先的最后一个位置是 View
,因此创建自定义基类还需要手动重建 DRF 和普通 Django 的类层次结构.提供自定义逻辑的 mixin 似乎是解决方案。然而,由于 mixin 只应该从 object 继承,PyCham 喜欢抱怨 self.request
和 self.kwargs
在 mixin 的方法中使用时不存在。
(不那么)简化的示例代码
class CustomMixinBase:
# class variables,mostly overridden in child mixins
thing_one: int = 2
thing_two: str = "one"
# a bunch of other @properties go here
def get(self,request,*args,**kwargs):
# pre-processing logic to determine which records to display
# anything that involves self.kwargs or self.request makes the PyCharm linter display an error
pre_process(self.kwargs.get("date"),self.request.GET.get("name"))
try:
super().get(request,**kwargs)
except:
# error-hadling logic goes here
# more code,if necessary
class ModelAMixin(CustomMixinBase):
thing_one = 7
class ModelBMixin(CustomMixinBase):
thing_one = 3
thing_two = "negative eighty-four"
class TemplateView(generic.ListView):
model = SharedMariaModel
template = "appname/generic.jinja"
# etc setting up Django template view variables
class ModelAView(TemplateView,ModelAMixin):
template = "appname/a.jinja"
def get_context_data(self):
"""
Overriding this function is why each model gets a separate class.
This app takes the underlying data from SharedMariaModel and displays it differently
depending on the model requested in the URL (eg. /city/4 vs /neighborhood/8)
"""
class ModelBView(TemplateView,ModelBMixin):
pass # really more of the same as above
class APIBase(ObjectMultipleModelAPIView):
def get_querylist(self,*params):
pass # output logic
class ModelAAPI(APIBase,ModelAMixin):
pass # you get the idea
class ModelBAPI(APIBase,ModelBMixin):
pass
问题
- 这似乎是高度重复的:每个模型都有一个 mixin、一个模板视图(mixin+template base)和一个 API 视图(API base+mixin)。感觉代码重复数据删除有很大的机会,尤其是在我的实际应用中,有 5 个模型而不是两个模型。
- 在
CustomMixinBase
中(大多数情况下),当我引用其混合类的另一个父类将具有的属性时,linter 不喜欢。除了将#noqa
添加到带有self.kwargs
的行尾之外,还有没有更好的方法可以让我的 IDE 关闭?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)