Django REST框架序列化ForeignKey和ManyToManyFields

2024-02-14

我有以下模型,我想将其序列化以通过 REST 公开:

class RehabilitationSession(models.Model):

    patient = models.ForeignKey('userprofiles.PatientProfile', null=True, blank=True,verbose_name='Paciente', related_name='patientprofile')

    slug = models.SlugField(max_length=100, blank=True)

    medical = models.ForeignKey('userprofiles.MedicalProfile', null=True, blank=True,
                        verbose_name='Médico tratante')
    therapist = models.ForeignKey('userprofiles.TherapistProfile', null=True, blank=True, verbose_name='Terapeuta')

    date_session_begin = models.DateTimeField(default=timezone.now(), verbose_name = 'Fecha de inicio')

    upper_extremity = MultiSelectField(
        max_length=255,
        choices=EXTREMITY_CHOICES,
        blank=False,
        verbose_name='Extremidad Superior'
    )

    affected_segment = models.ManyToManyField(AffectedSegment,verbose_name='Segmento afectado')

    movement = ChainedManyToManyField(
        Movement, #Modelo encadenado
        chained_field = 'affected_segment',
        chained_model_field = 'corporal_segment_associated',
        verbose_name='Movimiento'
    )

    metrics = models.ManyToManyField(Metric, blank=True, verbose_name='Métrica')
    date_session_end = models.DateTimeField(default=timezone.now(),      verbose_name = 'Fecha de finalización')
    period = models.CharField(max_length=25,blank=True, verbose_name='Tiempo de duración de la sesión')

    class Meta:
        verbose_name = 'Sesiones de Rehabilitación'

    def __str__(self):
        return "%s" % self.patient

要序列化我正在阅读的外键字段本文档 http://www.django-rest-framework.org/api-guide/relations/#hyperlinkedidentityfield

我的serializers.py是这样的:

from .models import RehabilitationSession
from rest_framework import serializers

class RehabilitationSessionSerializer(serializers.HyperlinkedModelSerializer):

    patient = serializers.HyperlinkedIdentityField(view_name='patientprofile',)

    class Meta:
        model = RehabilitationSession
        fields = ('url','id','patient',
              'date_session_begin','status','upper_extremity',

              'date_session_end', 'period','games','game_levels',
              'iterations','observations',)

我在用超链接身份字段 http://www.django-rest-framework.org/api-guide/relations/#hyperlinkedidentityfield,由于我的模型是序列化的HyperlinkedModelSerializer但是,我不清楚或者我仍然忽略当一个字段是时我应该如何序列化ForeignKey and ManyToManyField

My urls.py我在其中包含用于设置 api url 的路由的主文件是:

from django.conf.urls import url, include #patterns
from django.contrib import admin

from .views import home, home_files

# REST Framework packages
from rest_framework import routers
from userprofiles.views import UserViewSet, GroupViewSet, PatientProfileViewSet
from medical_encounter_information.views import RehabilitationSessionViewSet

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
router.register(r'rehabilitation-session', RehabilitationSessionViewSet)
router.register(r'patientprofile', PatientProfileViewSet)

urlpatterns = [
    url(r'^admin/', admin.site.urls),

    url(r'^chaining/', include('smart_selects.urls')),

    url(r'^$', home, name='home'),

    url(r'^', include('userprofiles.urls')),
    #Call the userprofiles/urls.py

    url(r'^', include('medical_encounter_information.urls' )),
    #Call the medical_encounter_information/urls.py

    #  which is a regular expression that takes the desired urls and passes as an argument
    # the filename, i.e. robots.txt or humans.txt.
    url(r'^(?P<filename>(robots.txt)|(humans.txt))$',
        home_files, name='home-files'),

    #REST Frameworks url's
    # Wire up our API using automatic URL routing.
    # Additionally, we include login URLs for the browsable API.

    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),

]

当我尝试访问 api rest 的 url 时,我在 cli 中收到以下消息:

     File "/home/bgarcial/.virtualenvs/neurorehabilitation_projects_dev/lib/python3.4/site-packages/rest_framework/relations.py", line 355, in to_representation
    raise ImproperlyConfigured(msg % self.view_name)
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "patientprofile". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
[08/Mar/2016 16:05:45] "GET /api/rehabilitation-session/ HTTP/1.1" 500 165647

在我的浏览器中我得到这个:

如何序列化发生在我身上的相同情况的ForeignKey和ManyToManyField? 此致


尝试将序列化器更改为

class RehabilitationSessionSerializer(serializers.HyperlinkedModelSerializer):

    patient = serializers.HyperlinkedIdentityField(view_name='patientprofile-detail',)

    class Meta:
        ...

路由器自动创建一个detail使用此名称查看ViewSet. See docs http://www.django-rest-framework.org/api-guide/relations/#hyperlinkedidentityfield对于参数view_name:

view_name- 应该用作关系目标的视图名称。如果您使用标准路由器类,这将是一个具有以下格式的字符串<model_name>-detail.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django REST框架序列化ForeignKey和ManyToManyFields 的相关文章

  • 从 ffmpeg 获取实时输出以在进度条中使用(PyQt4,stdout)

    我已经查看了很多问题 但仍然无法完全弄清楚 我正在使用 PyQt 并且希望能够运行ffmpeg i file mp4 file avi并获取流式输出 以便我可以创建进度条 我看过这些问题 ffmpeg可以显示进度条吗 https stack
  • if 语句未命中中的 continue 断点

    在下面的代码中 两者a and b是生成器函数的输出 并且可以评估为None或者有一个值 def testBehaviour self a None b 5 while True if not a or not b continue pri
  • 如何在 pytest 中将单元测试和集成测试分开

    根据维基百科 https en wikipedia org wiki Unit testing Description和各种articles https techbeacon com devops 6 best practices inte
  • 填充两个函数之间的区域

    import matplotlib pyplot as plt import numpy as np def domain x np arange 0 10 0 001 f1 lambda x 2 x x 2 0 5 plt plot x
  • 在Python中调整图像大小

    我有一张尺寸为 288 352 的图像 我想将其大小调整为 160 240 我尝试了以下代码 im imread abc png img im resize 160 240 Image ANTIALIAS 但它给出了一个错误TypeErro
  • 对图像块进行多重处理

    我有一个函数必须循环遍历图像的各个像素并计算一些几何形状 此函数需要很长时间才能运行 在 24 兆像素图像上大约需要 5 小时 但似乎应该很容易在多个内核上并行运行 然而 我一生都找不到一个有据可查 解释充分的例子来使用 Multiproc
  • 从 python 发起 SSH 隧道时出现问题

    目标是在卫星服务器和集中式注册数据库之间建立 n 个 ssh 隧道 我已经在我的服务器之间设置了公钥身份验证 因此它们只需直接登录而无需密码提示 怎么办 我试过帕拉米科 它看起来不错 但仅仅建立一个基本的隧道就变得相当复杂 尽管代码示例将受
  • 如何从Python中的字符串中提取变量名称和值

    我有一根绳子 data var1 id 12345 name John White python中有没有办法将var1提取为python变量 更具体地说 我对字典变量感兴趣 这样我就可以获得变量的值 id和name python 这是由提供
  • 首先对列表中最长的项目进行排序

    我正在使用 lambda 来修改排序的行为 sorted list key lambda item item lower len item 对包含元素的列表进行排序A1 A2 A3 A B1 B2 B3 B 结果是A A1 A2 A3 B
  • 将 matplotlib 颜色图集中在特定值上

    我正在使用 matplotlib 颜色图 seismic 绘制绘图 并且希望白色以 0 为中心 当我在不进行任何更改的情况下运行脚本时 白色从 0 下降到 10 我尝试设置 vmin 50 vmax 50 但在这种情况下我完全失去了白色 关
  • 在 pytube3 中获取 youtube 视频的标题?

    我正在尝试构建一个应用程序来使用 python 下载 YouTube 视频pytube3 但我无法检索视频的标题 这是我的代码 from pytube import YouTube yt YouTube link print yt titl
  • Python 将日志滚动到变量

    我有一个使用多线程并在服务器后台运行的应用程序 为了无需登录服务器即可监控应用程序 我决定包括Bottle http bottlepy org为了响应一些HTTP端点并报告状态 执行远程关闭等 我还想添加一种查阅日志文件的方法 我可以使用以
  • python Soap zeep模块获取结果

    我从 SOAP API 得到如下结果 client zeep Client wsdl self wsdl transport transport auth header lb E authenticate self login res cl
  • mac osx 10.8 上的初学者 python

    我正在学习编程 并且一直在使用 Ruby 和 ROR 但我觉得我更喜欢 Python 语言来学习编程 虽然我看到了 Ruby 和 Rails 的优点 但我觉得我需要一种更容易学习编程概念的语言 因此是 Python 但是 我似乎找不到适用于
  • 默认情况下,Keras 自定义层参数是不可训练的吗?

    我在 Keras 中构建了一个简单的自定义层 并惊讶地发现参数默认情况下未设置为可训练 我可以通过显式设置可训练属性来使其工作 我无法通过查看文档或代码来解释为什么会这样 这是应该的样子还是我做错了什么导致默认情况下参数不可训练 代码 im
  • 使用 PyTorch 分布式 NCCL 连接失败

    我正在尝试使用 torch distributed 将 PyTorch 张量从一台机器发送到另一台机器 dist init process group 函数正常工作 但是 dist broadcast 函数中出现连接失败 这是我在节点 0
  • 如何链接 Django 的“in”和“iexact”查询集字段查找?

    我有一个名字列表 例如 name list Alpha bEtA omegA 目前我有以下查询集 MyModel objects filter name in name list 我希望能够以不区分大小写的方式过滤名称 我的第一个想法是使用
  • 如何读取Python字节码?

    我很难理解 Python 的字节码及其dis module import dis def func x 1 dis dis func 上述代码在解释器中输入时会产生以下输出 0 LOAD CONST 1 1 3 STORE FAST 0 x
  • 迭代 pandas 数据框的最快方法?

    如何运行数据框并仅返回满足特定条件的行 必须在之前的行和列上测试此条件 例如 1 2 3 4 1 1 1999 4 2 4 5 1 2 1999 5 2 3 3 1 3 1999 5 2 3 8 1 4 1999 6 4 2 6 1 5 1
  • Scrapy Spider不存储状态(持久状态)

    您好 有一个基本的蜘蛛 可以运行以获取给定域上的所有链接 我想确保它保持其状态 以便它可以从离开的位置恢复 我已按照给定的网址进行操作http doc scrapy org en latest topics jobs html http d

随机推荐