Django REST框架序列化ForeignKey和ManyToManyFields [英] Django REST Framework Serializing ForeignKey and ManyToManyFields

查看:1078
本文介绍了Django REST框架序列化ForeignKey和ManyToManyFields的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型,我想通过REST进行序列化:

 类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édicotratante' )
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(
运动,#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 definalización')
period = models.CharField(max_length = 25,blank = True,verbose_name = 'b
$ b class Meta:
verbose_name ='Sesiones deRehabilitación'

def __str __(self):
return %s%self.patient

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



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

解决方案

尝试将序列化程序更改为

  class RehabilitationSessionSerializer(serializers.HyperlinkedModelSerializer):

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

class Meta:
...

路由器自动创建一个详细信息视图,此名称为 ViewSet 。请参阅 docs 参数 view_name


view_name - 应该是用作关系的目标。如果您使用的是标准的路由器类,那么它将是格式为< model_name> -detail 的字符串。



I have the following model, which I want serialize for expose via 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

To serialize the fields which are Foreign Key I am reading this documentation

My serializers.py is this:

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

I am using HyperlinkedIdentityField, due to my model is serialized with HyperlinkedModelSerializer but, I don't have clear or I still ignore how to should I serialize when one field is ForeignKey and ManyToManyField

My urls.py main file in which I include the route's for setup the api url's is:

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

]

When I try access to url of my api rest, I get the following message in 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

And in my browser I get this:

How to can I serialize a ForeignKey and ManyToManyField which happened to me the same situation? Best Regards

解决方案

Try changing your serializer to

class RehabilitationSessionSerializer(serializers.HyperlinkedModelSerializer):

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

    class Meta:
        ...

The router automatically creates a detail view with this name for a ViewSet. See docs for parameter 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.

这篇关于Django REST框架序列化ForeignKey和ManyToManyFields的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆