[英]Django abstract models - how to implement specific access in abstract view method?
Let's say I have an abstract model in Django, with two models extending off that. 假设我在Django中有一个抽象模型,然后扩展了两个模型。
Inside a Django Rest Framework generic view, how can I control creation of one of the two implementing models? 在Django Rest Framework通用视图内部,如何控制两个实现模型之一的创建?
My solution is below: 我的解决方案如下:
from enum import Enum
from rest_framework.views import APIView
class BazType(Enum):
FOO = 1
BAR = 2
class AbstractView(APIView):
def __init__self():
#Init code here
def _internal_method(self, django_model, this_type = BazType.FOO):
if this_type == BazType.FOO:
record, created = ConcreteModelOne.objects.get_or_create(some_field = django_model)
elif this.type == BazType.BAR:
record, created = ConcreteModelTwo.objects.get_or_create(some_field = django_model)
It works, but is there a way to get rid of the if/else block? 它有效,但是有办法摆脱if / else块吗? In other words, is there a way, from a subclass of
AbstractView
, to pass in some identifier for which model is required for the get_or_create
method call? 换句话说,有没有一种方法可以从
AbstractView
的子类中传递一些标识符,该标识符需要使用哪种模型进行get_or_create
方法调用?
You can create a mapping/dictionary that maps a model class to the values of each Enum
member, and use it in your _internal_method
for fetching the model class given the Enum
name: 您可以创建将模型类映射到每个
Enum
成员值的映射/字典,并在_internal_method
使用它来获取给定Enum
名称的模型类:
class AbstractView(APIView):
models_map = {1: ConcreteModelOne, 2: ConcreteModelTwo}
def __init__(self):
#Init code here
def _internal_method(self, django_model, this_type=BazType.FOO):
record, created = self.models_map[this_type].objects.get_or_create(some_field = django_model)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.