在Django

时间:2016-03-03 22:28:56

标签: json django django-models

我有以下模型:AffectedSegmentMovementMetricRehabilitationSession

在RehabilitationSession模型中,我正在生成其实例的JSONResponse。这些是我的模型代码:

  • AffectedSegment型号

    class AffectedSegment(models.Model):
        SEGMENTO_ESCAPULA = 'ESCAPULA'
        SEGMENTO_HOMBRO = 'HOMBRO'
        SEGMENTO_CODO = 'CODO'
        SEGMENTO_ANTEBRAZO = 'ANTEBRAZO'
        SEGMENTO_CARPO_MUNECA = 'CARPO_MUNECA'
        SEGMENTO_MANO = 'MANO'
        SEGMENTO_CHOICES = (
            (SEGMENTO_ESCAPULA, u'Escápula'),
            (SEGMENTO_HOMBRO, u'Hombro'),
            (SEGMENTO_CODO, u'Codo'),
            (SEGMENTO_ANTEBRAZO, u'Antebrazo'),
            (SEGMENTO_CARPO_MUNECA, u'Carpo/Muñeca'),
            (SEGMENTO_MANO, u'Mano'),
        )
        affected_segment = models.CharField(max_length=12, choices=SEGMENTO_CHOICES, blank=False, verbose_name='Segmento afectado')
    
        class Meta:
            verbose_name = 'Segmentos corporale'
    
  • Movement型号

    class Movement(models.Model):
        type = models.CharField(max_length=255,verbose_name='Tipo de movimiento')
        corporal_segment_associated = models.ManyToManyField(AffectedSegment, blank=False, verbose_name='Segmento corporal asociado')
    
        class Meta:
            verbose_name = 'Movimiento'
    
        def __str__(self):
            return "%s" % self.affected_segment
    
  • Metric型号

    class Metric(models.Model):
        name = models.CharField(max_length=255, blank=True, verbose_name='Nombre')
        equation = models.CharField(max_length=255, blank=True, verbose_name='Ecuación')
        min_value = models.DecimalField(max_digits=5,decimal_places=3, verbose_name='Valor mínimo')
        max_value = models.DecimalField(max_digits=5,decimal_places=3, verbose_name='Valor máximo')
    
    class Meta:
        verbose_name = 'Métrica'
    
    def __str__(self):
        return "{},{},{},{}".format(self.name, self.equation, self.min_value, self.max_value, )
    

在我的RehabilitationSession模型中,我将此ManyToMany字段与此前的模型一起使用:

from django.db import models
from smart_selects.db_fields import ChainedManyToManyField
class RehabilitationSession(models.Model):
    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')

在我的views.py中,我为这种JSONResponse个实例生成了RehabilitationSession ...

**重要的是要记住,在data列表中,我发送到我的模板list.html,字段为affected_segmentmovement和{与其他模型具有ManyToMany关系的{1}}

metrics

这是我的urls.py

from django.shortcuts import render
from django.views.generic import ListView
from .models import RehabilitationSession
from django.http import JsonResponse
# Create your views here.

class RehabilitationSessionsListView(ListView):
    model = RehabilitationSession
    template_name = 'list.html'

    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()

        format = self.request.GET.get('format', None)
        if format=='json':
            return self.json_to_response()

        context = self.get_context_data()
        return self.render_to_response(context)

    def json_to_response(self):

        data = list()
        data = [{
            'id':session.id,
            #'patient': print(session.patient.user.first_name),
            'patient':  session.patient.full_name,

            'medical':session.medical.full_name,
            'therapist':session.therapist.full_name,
            'date_session_begin':session.date_session_begin,
            'status':session.status,
            'upper_extremity': session.upper_extremity,


            # These three fields have ManyToMany relationships in
            # my RehabilitationSession model 
            'affected_segment':session.affected_segment,
            'movement':session.movement,
            'metrics':session.metrics,


            'date_session_end':session.date_session_end,
            'period':session.period,
            'games':session.games,
            'game_levels':session.game_levels,
            'iterations':session.iterations,
            'observations':session.observations,
        } for session in self.object_list]
        return JsonResponse(data, safe=False)


    def get_queryset(self):
        if self.kwargs.get('slug'):
            #Devolver un id
            queryset = self.model.objects.filter(slug=self.kwargs.get('slug'))
        else:
            queryset = super(RehabilitationSessionsListView, self).get_queryset()

        return queryset

当我在浏览器中尝试http://localhost:8000/rehabilitation-sessions/?format=json时,我收到此错误:

enter image description here

追溯就是这个

from django.conf.urls import include, url, patterns
from django.conf import settings
from .views import RehabilitationSessionsListView


urlpatterns = [
    url(r'^rehabilitation-sessions/$', RehabilitationSessionsListView.as_view(), name='sessions_list'),
    url(r'^rehabilitation-sessions/(?P<slug>[\w\-]+)/$', RehabilitationSessionsListView.as_view(), name='sessions_list'),

]

如何在我的JSONResponse中显示与其他模型具有ManyToMany关系的字段 /home/bgarcial/workspace/neurorehabilitation_projects/medical_encounter_information/views.py in get return self.json_to_response() ... ▼ Local vars Variable Value request <WSGIRequest: GET '/rehabilitation-sessions/?format=json'> format 'json' self <medical_encounter_information.views.RehabilitationSessionsListView object at 0x7fede00b1fd0> kwargs {} args () /home/bgarcial/workspace/neurorehabilitation_projects/medical_encounter_information/views.py in json_to_response return JsonResponse(data, safe=False) ... ▼ Local vars Variable Value self <medical_encounter_information.views.RehabilitationSessionsListView object at 0x7fede00b1fd0> data [{'affected_segment': <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7fede00c88d0>, 'date_session_begin': datetime.datetime(2016, 3, 3, 21, 16, 19, tzinfo=<UTC>), 'date_session_end': datetime.datetime(2016, 3, 3, 21, 16, 19, tzinfo=<UTC>), 'game_levels': '1. Escapando de la nave espacial', 'games': '1. Bonso', 'id': 6, 'iterations': 0, 'medical': 'Pablo Andres Agudelo Marenco', 'observations': 'Medical personal specialized considerations', 'patient': 'Sara Maria Salazar Sanchez', 'period': 'Por definirse', 'status': 'Planeada', 'therapist': 'Christian Andrés Diaz León', 'upper_extremity': ['Extremidad superior derecha']}, {'affected_segment': <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7fede00c87b8>, 'date_session_begin': datetime.datetime(2016, 3, 3, 21, 16, 19, tzinfo=<UTC>), 'date_session_end': datetime.datetime(2016, 3, 3, 21, 16, 19, tzinfo=<UTC>), 'game_levels': '1. Escapando de la nave espacial', 'games': '1. Bonso', 'id': 7, 'iterations': 0, 'medical': 'Pablo Andres Agudelo Marenco', 'observations': 'Medical personal specialized considerations', 'patient': 'Helmuth Trefftz Gómez', 'period': 'Por definirse', 'status': 'Planeada', 'therapist': 'Christian Andrés Diaz León', 'upper_extremity': ['Extremidad superior derecha']}] affected_segmentmovement

0 个答案:

没有答案