Pass objects to a serializer in Django Rest Framework - django-rest-framework

Here I have 2 objects recipe objects in my Recipe model. I am trying to understand what happens when I pass the recipe objects to my serializer like this. What system does to that objects? And what it returns?
recipes = Recipe.objects.all().order_by('-id')
serializer = RecipeSerializer(recipes, many=True)
And here is serializer:
class RecipeSerializer(serializers.ModelSerializer):
class Meta:
model = Recipe
fields = '__all__'

serializer = RecipeSerializer(recipes, many=True)
This means that you will take the data from the RecipeSerializer, not from the model recipe; in your case, that will be the same except the form (the serializer returns data as OrderedDict), but in case that the serializer have more data than the model, it's going to be more useful to call the serializer.data.

Related

Accessing ViewSet object list to provide extra context to serializer

I am attempting to add context to a serializer within a ModelViewSet which is dependent on the current paged object list in context. I'll explain with an example.
I am building a viewsets.ModelViewSet that lists Users and a list of favorite_foods. However- the list of user's favorite foods in some external microservice accessible via API. Building a ViewSet to collect objects and performing HTTP requests on each is trivial, we can do something like this:
class UserViewSet(viewsets.ViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserSerializer(serializers.ModelSerializer):
favorite_foods = serializers.SerializerMethodField()
def get_favorite_foods(self, instance):
# performs an HTTP call and returns a list[] of foods.
return evil_coupled_microservice_client.get_user_food_list(instance)
class Meta:
model = User
fields = ('id', 'name', 'favorite_foods')
The issue is (aside from some ugly infrastructure coupling) this is going to make an HTTP request count equivalent to the page size. Instead- it would be great if I could prefetch the favorite food lists for all users on the page in a single HTTP call, and just add them into context, like this:
class UserViewSet(viewsets.ViewSet):
def get_serializer_context(self):
context = super().get_serializer_context()
users = <-- This is where I want to know what users are in the current filtered, paginated response.
users_food_dict = evil_coupled_microservice_client.get_many_users_food_list(users)
context.update({'usesr_foods': users_food_dict})
return context
However- it doesn't appear there is any way to fetch the object list that's going to be serialized. Although (I'm fairly sure) get_serializer_context is called after the queryset is filtered and paginated, I'm not sure how to access it without doing some really hacking re-compiling of the queryset based on the query_params and other pieces attached to the class.
I'll post my current solution. It's not terrible, but I'm still hoping for a cleaner built-in.
class UserViewSet(viewsets.ViewSet):
...
def list(self, request, *args, **kwargs):
# Overrwite `ListModelMixin` and store current set
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
self.current_queryset = page
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
self.current_queryset = queryset
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
This is untested so far (not sure about functionality on Detail endpoints for instance) allows for the current_queryset to be fetched within the serializer context.

Create objects with nested serializer by using the UUID

I have a serializer like this:
class SureveyResponseSerializer(serializers.ModelSerializer):
respondent_profile = RespondentsProfileSerializer(read_only=True)
def create(self, validated_data):
... some stuff ...
return survey_response
class Meta:
model = SurveyResponse
fields = '__all__'
My problem here is dealing with creating and reading objects using the same serializer. For reading, I want to show the nested instance of respondent_profile with all its fields.
For a SurveyResponse (and adding a relation to an existing respondent_profile) I want to simply pass the UUID of an existing respondent_profile.
Is this possible or do I need two different serializers?

Django REST Framework: "NoneType object is not iterable" error when trying to use serializer.data construct from within Serializer Method Field?

I am using a model that consists of many fields. There is one field that is a property, and it returns an instance of a model. Something like the following:
class A(Model):
#property
def last_obj(self):
# Returns an object
The issue I'm having is that this property can return 2 different Model types. It can either return an object of type one, or an object of type two. This creates complications in the serializer. I have a serializer that consists of nested serializers. The two objects are similar enough that one serializer can be used over the other, but then the fields unique to them are not serialized.
class A_Serializer(Serializer):
class SerializerOne(CustomSerializer):
#Serializes certain fields in custom manner
class Meta:
model = models.one
exclude = ('id')
base_name = 'one'
class SerializerTwo(CustomSerializer):
#Serializes certain fields in custom manner
class Meta:
model = models.two
exclude = ('id')
base_name = 'two'
last_obj = SerializerOne() #This works, but not viable because of what I stated above
So my solution to be able to dynamically call the correct serializer, was to conditionally serialize the property within a serializer method field:
class A_Serializer(Serializer):
class SerializerOne(CustomSerializer):
#Serializes certain fields in custom manner
class Meta:
model = models.one
exclude = ('id')
base_name = 'one'
class SerializerTwo(CustomSerializer):
#Serializes certain fields in custom manner
class Meta:
model = models.two
exclude = ('id')
base_name = 'two'
def get_last_obj(self, instance):
if (isinstance(instance.last_obj, models.one)):
return self.SerializerOne(instance.last_obj).data
else:
return self.SerializerTwo(instance.last_obj).data
last_obj = SerializerMethodField() #Does not work
However, this solution creates the error "NoneType Object is not iterable" and it happens at
super(ReturnDict, self).__init__(*args, **kwargs) in rest_framework/utils/serializers_helpers.py in init which causes the error at return ReturnDict(ret, serializer=self) in rest_framework/serializers.py in data
I do not understand why calling a nested serializer like obj = Serializer() works, but calling the serializer explicitly like obj = Serializer(instance).data does not work in this situation. Can anyone figure out what I have been doing wrong? Thank you.
I have found out from here that when working with hyperlinked relations (which in my case was the CustomSerializer that SerializerOne and SerializerTwo were inheriting from), you must pass the request object through context. The reason why obj = Serializer() works, but obj = Serializer(instance).data does not work is that in the former, the request object is automatically added through context through DRF. While in the latter, it is being explicitly called so you must pass context with the request object manually. So for me to get it working, I did:
return self.SerializerOne(instance.last_obj, context={'request': self.context['request']}).data
inside the serializer method field.

Serializing inside method field in Django REST framework

For example, I have two models: Model1 and Model2. They are not related directly to each-other by any key-field on a model level. For both models I have serializers. I am searching the way to have Model2 queryset in Model1 serializer. For example:
GET /api/model1/01
According to Model1 ID in request I can make query for Model2 objects that I need to be sent in response. For now I have solution that I don't like: in Model1 serializer I have method field that returns a list of objects. Is there any way to use Model2 serializer in method field of Serializer1 or any other solution for my case?
Solution-1: Using Model2Serializer in a Model1's SerializerMethodField()
In this method, we define a model2_data SerializerMethodField() field in the Model1Serializer. There, we will first fetch all the Model2 objects using the current Model1 object. Then we initialize the Model2Serializer with many=True argument and pass all the obtained Model2 instances. To return the serialized representation of Model2 objects, we access the .data property.
class Model1Serializer(serializers.ModelSerializer):
model2_data = serializers.SerializerMethodField() # define separate field
class Meta:
model = Model1
fields = [.., 'model2_data']
def get_model2_data(self, obj):
# here write the logic to get the 'Model2' objects using 'obj'
# initialize the 'Model2Serializer'
model2_serializer = Model2Serializer(model2_objs, many=True)
# return the serialized representation of 'Model2' objs
return model2_serializer.data
Solution-2: Overriding the retrieve method
Another option is to override the retrieve method and add the model2_data to your response along with original response.
class MyView(generics.RetrieveAPIView):
serializer_class = Model1Serializer
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
# get the original serialized data
serialized_data = serializer.data
# get the 'Model2' objects using 'serializer.instance'
model2_serializer = Model2Serializer(model2_objs, many=True)
model2_data = model2_serializer.data
# add the serialized representation of `Model2` objs
serialized_data['model2_data'] = model2_data
return Response(serialized_data)
PS: I know these solutions are not clean. Had the two models been related, we could have approached the problem in a more cleaner way.

Django Rest Framework - Exclude field from related object

I have two related models and serializers for both of them. When I am serializing one of these models (the serializer has a depth of 1) the result includes some fields from the related object that should't be visible. How an I specify which serializer to use for the relation? Or is there anyway to tell Rest Framework to exclude some fields from the related object?
Thank you,
I think one way would be to create an extra serializer for the model where you want to return only limited number of fields and then use this serializer in the serializer of the other model. Something like this:
class MyModelSerializerLimited(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('field1', 'field2') #fields that you want to display
Then in the other serializer use the MyModelSerializerLimited:
class OtherModelSerializer(serializers.ModelSerializer):
myfield = MyModelSerializerLimited()
class Meta:
model = OtherModel
fields = ('myfield', ...)
depth = 1
You could override restore_fields method on serializer. Here in restore_fields method you can modify list of fields - serializer.fields - pop, push or modify any of the fields.
eg: Field workspace is read_only when action is not 'create'
class MyPostSerializer(ModelSerializer):
def restore_fields(self, data, files):
if (self.context.get('view').action != 'create'):
self.fields.get('workspace').read_only=True
return super(MyPostSerializer, self).restore_fields(data, files)
class Meta:
model = MyPost
fields = ('id', 'name', 'workspace')

Resources