繁体   English   中英

Django抽象模型-如何在抽象视图方法中实现特定的访问?

[英]Django abstract models - how to implement specific access in abstract view method?

假设我在Django中有一个抽象模型,然后扩展了两个模型。

在Django Rest Framework通用视图内部,如何控制两个实现模型之一的创建?

我的解决方案如下:

    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)

它有效,但是有办法摆脱if / else块吗? 换句话说,有没有一种方法可以从AbstractView的子类中传递一些标识符,该标识符需要使用哪种模型进行get_or_create方法调用?

您可以创建将模型类映射到每个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM