2

I have the following models: AffectedSegment, Movement, Metric and RehabilitationSession

In the RehabilitationSession model I am generating a JSONResponse of their instances. These are my models code:

  • AffectedSegment model

    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 model

    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 model

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

In my RehabilitationSession model I have this ManyToMany fields with the previous models of this way:

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

In my views.py I am generating a JSONResponse for the RehabilitationSession instances of this way ...

**It's important remember that in the data list that I sent to my template list.html here, are the fields affected_segment, movement and metrics which have ManyToMany relationships with other models

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

This is my urls.py

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

]

When I try in my browser the http://localhost:8000/rehabilitation-sessions/?format=json , I get this error:

enter image description here

The traceback is this

    /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']}]

How to can I show in my JSONResponse the fields affected_segment, movement and metrics which have ManyToMany relationships with other models?

bgarcial
  • 2,915
  • 10
  • 56
  • 123
  • 1
    I'm just wondering something: Why do you create the JSON instead of using Django Rest Framework Serializers class ? It would be more easier and you can of course serialize the ManyToManyField. – Cagatay Barin Mar 04 '16 at 00:36
  • @ÇağatayBarınI am trying with `djangorestframework` and I have some problem in ForeingKey and ManyToMany fields. If you can see in your time I would, and I will be very grateful http://stackoverflow.com/questions/35874888/django-rest-framework-serializing-foreignkey-and-manytomanyfields :) – bgarcial Mar 08 '16 at 18:17
  • 1
    I guess someone else answered your problem. Sorry for the late response body :) – Cagatay Barin Mar 08 '16 at 19:29
  • @ÇağatayBarın Don't worry Sir. Thanks a lot for you for the restframework recommendation :D – bgarcial Mar 08 '16 at 19:33
  • 1
    I'm happy if it's working for you. You can let me know if you have another problem. Happy coding! – Cagatay Barin Mar 08 '16 at 19:35
  • @ÇağatayBarın Although don't nothing relation with the django rest framework, I don't know if you can orient me in this question http://stackoverflow.com/questions/35778497/how-to-apply-debug-to-the-django-admin-forms-fields. And my apologies for the petition. Thanks. – bgarcial Mar 11 '16 at 16:40

0 Answers0