Django:外部类的集成?

时间:2018-10-28 09:12:50

标签: django django-rest-framework

我对这个愚蠢的问题事先表示歉意。 :)

我正在尝试使用Django rest框架创建REST API。该API位于一种算法之上,我一直在尝试将其集成到Django框架中,但是正确执行此操作令人沮丧,我怀疑这是由于我对Django的了解不足。

这是我的代码段。

models.py

from django.db import models                                                                         

class my_model(models.Model):
  dob = models.TextField()
  response = models.TextField()
  field1 = models.TextField()

class Meta:
  ordering = ('dob','response','field1')

serializers.py

import re
import numpy as np
from django_rest.quickstart.models import my_model
from rest_framework import serializers
from rest_framework.renderers import JSONRenderer
from my_algorithm import my_algorithm

class myAlgorithmSerializer(serializers.ModelSerializer):
  my_algorithm_instance = my_algorithm()
  response = serializers.SerializerMethodField('myAlgorithm_wrapper',my_algorithm_instance)
  field1 = serializers.SerializerMethodField('field1_wrapper', my_algorithm_instance)

  def myAlgorithm_wrapper(self, my_model, my_algorithm_instance):

    # Get the inputs.                                                                                                                                                                                   
    dob = str(my_model.dob)

    components = np.array(re.split('/| |:', dob)).astype(int)

    birth_day = components[0]
    birth_month = components[1]
    birth_year = components[2]
    birth_hour = components[3]
    birth_minutes = components[4]

    my_algorithm_instance.set_birthdate_time(\
                birth_year, birth_month, birth_day,\
                birth_hour, birth_minutes)

    my_algorithm_instance.run()

    my_structure = my_algorithm_instance.my_struct
    content = JSONRenderer().render(my_structure)

    return(content)

  def field1_wrapper(self, my_model, my_algorithm_instance):
    another_structure = my_algorithm_instance.another_pillar_struct
    content = JSONRenderer().render(another_structure)
    return(content)

  class Meta:
    model = Bazhi
    fields = ('dob', 'response', 'field1')

我收到一条错误消息,从本质上说,方法'myAlgorithm_wrapper'和'field1_wrapper'仅接受2个参数,而不接受必需的3个参数。两个包装器都需要我的算法实例,尽管它们应该在范围内在这些方法中,它们被报告为“丢失”。下面的堆栈跟踪。

Traceback (most recent call last):
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/core/management/base.py", line 379, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/core/management/base.py", line 366, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/core/checks/registry.py", line 71, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/utils/functional.py", line 37, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/urls/resolvers.py", line 533, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/utils/functional.py", line 37, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/pi/myAlgorithm/lib/python3.5/site-packages/django/urls/resolvers.py", line 526, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/pi/myAlgorithm/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 673, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/pi/myAlgorithm_app/myAlgorithm/django_rest/urls.py", line 29, in <module>
    from django_rest.quickstart import views
  File "/home/pi/myAlgorithm_app/myAlgorithm/django_rest/quickstart/views.py", line 8, in <module>
    from django_rest.quickstart.serializers import UserSerializer, GroupSerializer, myAlgorithmSerializer
  File "/home/pi/myAlgorithm_app/myAlgorithm/django_rest/quickstart/serializers.py", line 25, in <module>
    class myAlgorithmSerializer(serializers.ModelSerializer):
  File "/home/pi/myAlgorithm_app/myAlgorithm/django_rest/quickstart/serializers.py", line 27, in myAlgorithmSerializer
    response = serializers.SerializerMethodField('myAlgorithm_wrapper', my_algorithm_instance)
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

我应该将其合并到models.py中,而不是使用管理器吗?该文档似乎没有包括检索特定字段的方法-就我而言,是dob并进行处理。即使这种方法是合理的,我也会像在序列化程序中那样在范围界定方面遇到麻烦吗?任何指导将不胜感激。

非常感谢!
埃德

1 个答案:

答案 0 :(得分:0)

该问题与您的外部类完全没有关系。如回溯所示,问题与SerializerMethodField的参数有关。像所有序列化程序字段一样,to应该使用关键字参数,而不是位置参数;并且该字段的主要关键字arg为method_name

我不明白您通过将算法实例传递到字段中想要达到的目的。即使可行,文档也指出从该字段引用的方法应具有单个参数,该对象将被序列化。如果想法是两种方法都共享算法实例,那么也许应该在序列化器的__init__方法中实例化它,然后在方法中引用它:

class myAlgorithmSerializer(serializers.ModelSerializer):
  response = serializers.SerializerMethodField(method_name='myAlgorithm_wrapper')
  field1 = serializers.SerializerMethodField(method_name='field1_wrapper')

  def __init__(self, *args, **kwargs):
     self.my_algorithm_instance = my_algorithm()
     super().__init__(*args, **kwargs)

  def myAlgorithm_wrapper(self, my_model):
     ...
     # refer to self.my_algorithm_instance
     ...