Additional variables (context) on a ModelSerializer?

4,351 views
Skip to first unread message

George Mamalakis

unread,
Feb 7, 2014, 3:52:32 AM2/7/14
to django-res...@googlegroups.com
Hello everybody,

Is there I way I could process more context on my ModelSerializer other than that of my model? I wish, for example, to pass additional information on listing, that are not stored in the model my Serializer is connected.

Thanx all in advance!

Denis Cornehl

unread,
Feb 7, 2014, 3:55:35 AM2/7/14
to django-res...@googlegroups.com
Hi George, 

you can override "get_serializer_context" in your view. Then you will be able to access the information inside the serializer by using self.context. 

Alternative is to provide the data in view-methods. The view is in the serializer-context  by default (self.context['view]). 



2014-02-07 George Mamalakis <mam...@gmail.com>:
Hello everybody,

Is there I way I could process more context on my ModelSerializer other than that of my model? I wish, for example, to pass additional information on listing, that are not stored in the model my Serializer is connected.

Thanx all in advance!

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Freundliche Grüße

Denis Cornehl
Simon-Dach-Str. 7 / 10245 Berlin

M: +49 (151) 25 25 1450
@: denis....@gmail.com

X: http://xing.to/dc

George Mamalakis

unread,
Feb 7, 2014, 4:34:10 AM2/7/14
to django-res...@googlegroups.com
Hi Denis,

Thank you for your immediate and precise answer! I will try the methods you are proposing to me. Before doing so, is there any documentation on any of your methods that I could read?


On Friday, February 7, 2014 10:55:35 AM UTC+2, Denis Cornehl wrote:
Hi George, 

you can override "get_serializer_context" in your view. Then you will be able to access the information inside the serializer by using self.context. 

Alternative is to provide the data in view-methods. The view is in the serializer-context  by default (self.context['view]). 



2014-02-07 George Mamalakis <mam...@gmail.com>:
Hello everybody,

Is there I way I could process more context on my ModelSerializer other than that of my model? I wish, for example, to pass additional information on listing, that are not stored in the model my Serializer is connected.

Thanx all in advance!

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

Denis Cornehl

unread,
Feb 7, 2014, 4:34:59 AM2/7/14
to django-res...@googlegroups.com


2014-02-07 George Mamalakis <mam...@gmail.com>:
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.

George Mamalakis

unread,
Feb 7, 2014, 6:27:59 AM2/7/14
to django-res...@googlegroups.com
Thanx again!


On Friday, February 7, 2014 11:34:59 AM UTC+2, Denis Cornehl wrote:


2014-02-07 George Mamalakis <mam...@gmail.com>:
Hi Denis,

Thank you for your immediate and precise answer! I will try the methods you are proposing to me. Before doing so, is there any documentation on any of your methods that I could read?


On Friday, February 7, 2014 10:55:35 AM UTC+2, Denis Cornehl wrote:
Hi George, 

you can override "get_serializer_context" in your view. Then you will be able to access the information inside the serializer by using self.context. 

Alternative is to provide the data in view-methods. The view is in the serializer-context  by default (self.context['view]). 



2014-02-07 George Mamalakis <mam...@gmail.com>:

Hello everybody,

Is there I way I could process more context on my ModelSerializer other than that of my model? I wish, for example, to pass additional information on listing, that are not stored in the model my Serializer is connected.

Thanx all in advance!

--




George Mamalakis

unread,
Feb 10, 2014, 6:31:14 AM2/10/14
to django-res...@googlegroups.com
Denis,

I tried to use get_serializer_context for my project, but I got a bit confused, since the documentation you proposed me was for method-views. Then I found this link explaining how I can override get_serializer_context for GenericViews and tried to apply it on my case, with no luck. Here is my scenario:

My models:

class Report(models.Model):
    name = models.CharField(max_length=150, blank=True, null=True)
    year = models.DateField(blank=True, null=True)
    is_final = models.BooleanField(blank=True, default=False, db_index=True)


class Section(models.Model):
    name = models.CharField(max_length=500)
    text = models.Text(blank=True, null=True)
    report = models.ForeignKey(Report, related_name='sections')

class Data(models.Model):
    name = models.CharField(max_length=150)
    text = models.ForeignKey(RichText, blank=True, null=True, related_name='%(app_label)s_%(class)s_start_text')
    section = models.ForeignKey(Section, related_name='data')
    saved = models.BooleanField(default=False, db_index=True)

So, in short, I have report objects that have associated sections to them and each section has associated data. 

My views are as follows:

class ReportViewSet(viewsets.ModelViewSet):
    queryset = Report.objects.all()
    serializer_class = serializers.ReportSerializer

class SectionViewSet(viewsets.ModelViewSet):
    queryset = Section.objects.all()
    serializer_class = serializers.SectionSerializer

class DataViewSet(viewsets.ModelViewSet):
    queryset = Data.objects.all()
    serializer_class = serializers.DataSerializer

And my serializers are as follows:

class DataSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = EmissionGroup

class SectionSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Section

class ReportSerializer(serializers.HyperlinkedModelSerializer):
     sections = SectionSerializer(many=True, read_only=True)

     class Meta:
        model = Report

What I am trying to do is to add an extra boolean field on my SectionSerializer (named, eg. all_saved), whose value will be True if all its related Data.saved values are also True.

When I tried to override get_serializer_context on SectionViewSet to test how it works, I've made the following changes:

class SectionViewSet(viewsets.ModelViewSet):
    queryset = Section.objects.all()
    serializer_class = serializers.SectionSerializer

    def get_serializer_context(self):
        context = super(SectionViewSet, self).get_serializer_context()
        context.update({'x': '11'})
        return context


class SectionSerializer(serializers.HyperlinkedModelSerializer):
    all_saved = serializers.SerializerMethodField('get_x')
    
    def get_x(self, instance):
        return self.context['xx']

    class Meta:
        model = Section

Then when I was viewing /section/ everything worked as expected, but when I was viewing /report/ I was getting the error:

KeyError at /report/
'x'
Request Method: GET
Django Version: 1.6.1
Exception Type: KeyError
Exception Value: 'x'
Exception Location: /path/to/serializers.py in get_x, line 129

And the truth is that SectionViewSet.get_serializer_context() never gets called (I can infer this since my debugger never stops at a break-point that I am placing in this function).

What is the correct way of using additional context in my case?

Thanx again for your time!

On Friday, February 7, 2014 10:55:35 AM UTC+2, Denis Cornehl wrote:
Hi George, 

you can override "get_serializer_context" in your view. Then you will be able to access the information inside the serializer by using self.context. 

Alternative is to provide the data in view-methods. The view is in the serializer-context  by default (self.context['view]). 



2014-02-07 George Mamalakis <mam...@gmail.com>:
Hello everybody,

Is there I way I could process more context on my ModelSerializer other than that of my model? I wish, for example, to pass additional information on listing, that are not stored in the model my Serializer is connected.

Thanx all in advance!

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.

George Mamalakis

unread,
Feb 10, 2014, 6:34:04 AM2/10/14
to django-res...@googlegroups.com
Correction. On:
    def get_x(self, instance):
        return self.context['xx']

what I am really using is:

    def get_x(self, instance):
        return self.context['x']

Sorry, this was just a spelling mistake.

Denis Cornehl

unread,
Feb 10, 2014, 6:38:22 AM2/10/14
to django-res...@googlegroups.com
Hi George, 

have you added "x" to the context of the reportviewset? 

The context is created in the viewset and is used by the serializers. 
In the ReportSerializer you have a foreignkey to the SectionSerializer, but since you are (at this moment) in the ReportViewSet, the context does not contain "x". 




--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.

George Mamalakis

unread,
Feb 10, 2014, 7:08:28 AM2/10/14
to django-res...@googlegroups.com
Hi Denis,

Thanx again for you immediate reply. Nevertheless, I am not sure how to do what you are suggesting me to do. In my ReportSerializer I have a nested SectionSerializer (sections) to relate section objects with reports. Each section object should contain some additional information about the data objects that are associated with them. Hence, the additional context I am trying to pass is Section-related, not Report-related. Therefore, I am not sure how I can pass in my ReportViewSet Data information on each Report object's nested Section object.


On Monday, February 10, 2014 1:38:22 PM UTC+2, Denis Cornehl wrote:
Hi George, 

have you added "x" to the context of the reportviewset? 

The context is created in the viewset and is used by the serializers. 
In the ReportSerializer you have a foreignkey to the SectionSerializer, but since you are (at this moment) in the ReportViewSet, the context does not contain "x". 


2014-02-10 12:34 GMT+01:00 George Mamalakis <mam...@gmail.com>:
Correction. On:
    def get_x(self, instance):
        return self.context['xx']

what I am really using is:

    def get_x(self, instance):
        return self.context['x']

Sorry, this was just a spelling mistake.

On Friday, February 7, 2014 10:52:32 AM UTC+2, George Mamalakis wrote:
Hello everybody,

Is there I way I could process more context on my ModelSerializer other than that of my model? I wish, for example, to pass additional information on listing, that are not stored in the model my Serializer is connected.

Thanx all in advance!

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.
Reply all
Reply to author
Forward
0 new messages