python - Django REST Framework 序列化 ForeignKey 和 ManyToManyFields

标签 python django serialization django-models django-rest-framework

我有以下模型,我想将其序列化以通过 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

要序列化我正在阅读的外键字段 this documentation

我的 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',)

我正在使用 HyperlinkedIdentityField ,由于我的模型是用 HyperlinkedModelSerializer 序列化的,但是,我不清楚或者我仍然忽略了当一个字段是 ForeignKeyManyToManyField 时我应该如何序列化

我的 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

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

enter image description here

如何序列化发生在我身上的相同情况的 ForeignKey 和 ManyToManyField? 最好的问候

最佳答案

尝试将序列化程序更改为

class RehabilitationSessionSerializer(serializers.HyperlinkedModelSerializer):

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

    class Meta:
        ...

路由器自动创建一个detail使用此名称查看 ViewSet .参见 docs对于参数 view_name :

view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format <model_name>-detail.

关于python - Django REST Framework 序列化 ForeignKey 和 ManyToManyFields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35874888/

相关文章:

c# - 在序列化时调用 GetObjectData

python - 使用Python组合包含整数的列中的列表行

python - 查找并替换为以小写字母开头的正确句子案例句子。正则表达式或崇高

django - 在 Django 中注释 value() 查询

c++ - boost 套接字的序列化

dart - Dart中抽象类型的反序列化

python - 遍历一组字典 - python - 基本搜索

python - 如何在 Django 中记录一个文件

python - Django+PostgreSql : Can I run out of id/pk?

python - 如何在python中安装mysqlclient?