Django:类型错误。预期pk值,收到str

时间:2019-03-22 17:18:11

标签: django django-rest-framework foreign-keys serializer

我正在使用Django Rest Framework执行get()和post()到现有数据库。数据库没有“ id”字段。它具有适用于所有表的复合主键,我无法修改表的架构。带邮递员的get()可以按预期工作,但是面临post()的问题。我在三个模型之间嵌套了外键关系。

问题: 1.使用可浏览的API,当我单击UI中提供的链接时,它会引发错误-(1054, "Unknown column 'test_suite.id' in 'field list'") [下面附有跟踪信息]

  1. 带有主持人的post()也抛出下面给出的错误。

models.py

class TestSuiteModel(models.Model):
    team_name = models.ForeignKey(TeamModel, on_delete=models.DO_NOTHING, db_column='team_name')
    template_name = models.ForeignKey(EmailTemplatesModel, on_delete=models.DO_NOTHING, db_column='template_name')
    suite_name = models.CharField(max_length=100)
    # Other Fields

    class Meta:
        managed = False
        db_table = 'test_suite'
        unique_together = (('team_name', 'suite_name'),)

class TestCaseModel(models.Model):
    team_name = models.ForeignKey(TestSuiteModel, on_delete=models.DO_NOTHING, db_column='team_name')
    suite_name = models.ForeignKey(TestSuiteModel, on_delete=models.DO_NOTHING, db_column='suite_name')
    test_type = models.ForeignKey(TestCaseTypeModel, on_delete=models.DO_NOTHING)
    # Other Fields

    class Meta:
        managed = False
        db_table = 'test_case'
        unique_together = (('team_name', 'suite_name', 'case_name'),)

class TeamModel(models.Model):
    team_name = models.CharField(primary_key=True, max_length=30)
    description = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'team'


class TestCaseTypeModel(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=200, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'test_case_type'

serializers.py

class TestCaseSerializer(serializers.ModelSerializer):
    logger.info(" inside TestCaseSerializer " )
    class Meta:
        model = models.TestCaseModel
        fields = ['team_name', 'suite_name', 'case_name', 'description', 'run_level', 'stop_on_failure', 'test_type_id']

    def to_representation(self, obj):
        if isinstance(obj, dict):  # get methods
            return obj
        else:
            self.fields['team_name'] = TestSuiteSerializer()
            self.fields['suite_name'] = TestSuiteSerializer()
            self.fields['test_type_id'] = TestCaseTypeSerializer()
            return super(TestCaseSerializer, self).to_representation(obj)

class TestSuiteSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.TestSuiteModel
        fields = ['team_name','suite_name', 'description','schedule','email_list_ok','email_list_fail','template_name']

    def to_representation(self, obj):
        if isinstance(obj, dict): 
            return obj
        else:
            self.fields['team_name'] = TeamSerializer()
            self.fields['template_name'] = EmailTemplatesSerializer()
            return super(TestSuiteSerializer, self).to_representation(obj)

class TeamSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.TeamModel
        fields = '__all__'

views.py

class TestCaseViewSet(viewsets.ModelViewSet):
    queryset = models.TestCaseModel.objects.values('team_name', 'suite_name', 'case_name', 'description', 'run_level', 'stop_on_failure', 'test_type_id')
    serializer_class = serializers.TestCaseSerializer

class TestSuiteViewSet(viewsets.ModelViewSet):
    queryset = models.TestSuiteModel.objects.values('team_name','suite_name', 'description','schedule','email_list_ok','email_list_fail','template_name')
    serializer_class = serializers.TestSuiteSerializer(queryset)

class TeamViewSet(viewsets.ModelViewSet):
    queryset = models.TeamModel.objects.all()
    serializer_class = serializers.TeamSerializer

urls.py

router = routers.DefaultRouter()
router.register(r'teams', views.TeamViewSet)
router.register(r'test_suites', views.TestSuiteViewSet)
router.register(r'test_cases', views.TestCaseViewSet)
urlpatterns = [
    url(r'^dqf_api/', include(router.urls)),
]

当我单击api链接时,[问题1] UI错误回溯

File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute
  85.                 return self.cursor.execute(sql, params)

File "/usr/local/lib/python3.6/dist-packages/django/db/backends/mysql/base.py" in execute
  71.             return self.cursor.execute(query, args)

File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py" in execute
  206.         res = self._query(query)

File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py" in _query
  312.         db.query(q)

File "/usr/local/lib/python3.6/dist-packages/MySQLdb/connections.py" in query
  224.         _mysql.connection.query(self, query)

The above exception ((1054, "Unknown column 'test_suite.id' in 'field list'")) was the direct cause of the following exception:

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  158.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  156.                 response = response.render()

File "/usr/local/lib/python3.6/dist-packages/django/template/response.py" in render
  106.             self.content = self.rendered_content

File "/usr/local/lib/python3.6/dist-packages/rest_framework/response.py" in rendered_content
  72.         ret = renderer.render(self.data, accepted_media_type, context)

File "/usr/local/lib/python3.6/dist-packages/rest_framework/renderers.py" in render
  733.         context = self.get_context(data, accepted_media_type, renderer_context)

File "/usr/local/lib/python3.6/dist-packages/rest_framework/renderers.py" in get_context
  704.             'post_form': self.get_rendered_html_form(data, view, 'POST', request),

File "/usr/local/lib/python3.6/dist-packages/rest_framework/renderers.py" in get_rendered_html_form
  522.             return self.render_form_for_serializer(serializer)

File "/usr/local/lib/python3.6/dist-packages/rest_framework/renderers.py" in render_form_for_serializer
  532.             {'style': {'template_pack': 'rest_framework/horizontal'}}

File "/usr/local/lib/python3.6/dist-packages/rest_framework/renderers.py" in render
  383.         return template.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/backends/django.py" in render
  61.             return self.template.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render
  175.                     return self._render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in _render
  167.         return self.nodelist.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/defaulttags.py" in render
  211.                     nodelist.append(node.render_annotated(context))

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/defaulttags.py" in render
  314.                 return nodelist.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/library.py" in render
  192.         output = self.func(*resolved_args, **resolved_kwargs)

File "/usr/local/lib/python3.6/dist-packages/rest_framework/templatetags/rest_framework.py" in render_field
  90.     return renderer.render_field(field, style)

File "/usr/local/lib/python3.6/dist-packages/rest_framework/renderers.py" in render_field
  362.         return template.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/backends/django.py" in render
  61.             return self.template.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render
  175.                     return self._render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in _render
  167.         return self.nodelist.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/defaulttags.py" in render
  161.                 values = self.sequence.resolve(context, True)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in resolve
  676.                 obj = self.var.resolve(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in resolve
  802.             value = self._resolve_lookup(context)

File "/usr/local/lib/python3.6/dist-packages/django/template/base.py" in _resolve_lookup
  864.                             current = current()

File "/usr/local/lib/python3.6/dist-packages/rest_framework/relations.py" in iter_options
  222.             self.get_choices(cutoff=self.html_cutoff),

File "/usr/local/lib/python3.6/dist-packages/rest_framework/relations.py" in get_choices
  209.             for item in queryset

File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in __iter__
  272.         self._fetch_all()

File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in _fetch_all
  1179.             self._result_cache = list(self._iterable_class(self))

File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in __iter__
  54.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)

File "/usr/local/lib/python3.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  1064.             cursor.execute(sql, params)

File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in execute
  100.             return super().execute(sql, params)

File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in execute
  68.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute_with_wrappers
  77.         return executor(sql, params, many, context)

File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute
  85.                 return self.cursor.execute(sql, params)

File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute
  85.                 return self.cursor.execute(sql, params)

File "/usr/local/lib/python3.6/dist-packages/django/db/backends/mysql/base.py" in execute
  71.             return self.cursor.execute(query, args)

File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py" in execute
  206.         res = self._query(query)

File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py" in _query
  312.         db.query(q)

File "/usr/local/lib/python3.6/dist-packages/MySQLdb/connections.py" in query
  224.         _mysql.connection.query(self, query)

Exception Type: OperationalError at /dqf_api/test_cases/
Exception Value: (1054, "Unknown column 'test_suite.id' in 'field list'")

[问题2] postman()中的post()错误

有效载荷:

{
        "team_name":"ede",
        "suite_name": "dummy",
        "case_name": "ede case",
        "description": "",
        "run_level": 1,
        "stop_on_failure": false,
        "test_type_id": 1
    }

错误:

{
    "team_name": [
        "Incorrect type. Expected pk value, received str."
    ],
    "suite_name": [
        "Incorrect type. Expected pk value, received str."
    ]
}

我们非常感谢您的帮助。我是使用Django和DRF的新手

0 个答案:

没有答案