How do i serialize objects during enrichment with stream-django and django rest framework? - django-rest-framework

Im using stream-django with django REST framework and the enriched activities are throwing "not JSON serializable" on the objects returned from enrichment, which is as expected as they have not gone through any serializing.
How do i customize the enrichment process so that it returns a serialized object from my drf serializer and not the object itself?
Some example data, not enriched:
"is_seen": false,
"is_read": false,
"group": "19931_2016-04-04",
"created_at": "2016-04-04T08:53:42.601",
"updated_at": "2016-04-04T11:33:26.140",
"id": "0bc8c85a-fa59-11e5-8080-800005683205",
"verb": "message",
"activities": [
{
"origin": null,
"verb": "message",
"time": "2016-04-04T11:33:26.140",
"id": "0bc8c85a-fa59-11e5-8080-800005683205",
"foreign_id": "chat.Message:6",
"target": null,
"to": [
"notification:1"
],
"actor": "auth.User:1",
"object": "chat.Message:6"
}
The view:
def get(self, request, format=None):
user = request.user
enricher = Enrich()
feed = feed_manager.get_notification_feed(user.id)
notifications = feed.get(limit=5)['results']
enriched_activities=enricher.enrich_aggregated_activities(notifications)
return Response(enriched_activities)

I solved it by doing the following:
property tag on the model that returns the serializer class
#property
def activity_object_serializer_class(self):
from .serializers import FooSerializer
return FooSerializer
Then used this to serialize the enriched activities. Supports nesting.
#staticmethod
def get_serialized_object_or_str(obj):
if hasattr(obj, 'activity_object_serializer_class'):
obj = obj.activity_object_serializer_class(obj).data
else:
obj = str(obj) # Could also raise exception here
return obj
def serialize_activities(self, activities):
for activity in activities:
for a in activity['activities']:
a['object'] = self.get_serialized_object_or_str(a['object'])
# The actor is always a auth.User in our case
a['actor'] = UserSerializer(a['actor']).data
return activities
and the view:
def get(self, request, format=None):
user = request.user
enricher = Enrich()
feed = feed_manager.get_notification_feed(user.id)
notifications = feed.get(limit=5)['results']
enriched_activities = enricher.enrich_aggregated_activities(notifications)
serialized_activities = self.serialize_activities(enriched_activities)
return Response(serialized_activities)

The enrich step replaces string references into full Django model instances.
For example: the string "chat.Message:6" is replaced with an instance of chat.models.Message (same as Message.objects.get(pk=6)).
By default DRF does not know how to serialize Django models and fails with a serialization error. Luckily serializing models is a very simple task when using DRF. There is a built-in serializer class that is specific to Django models (serializers.ModelSerializer).
The documentation of DRF explains this process in detail here: http://www.django-rest-framework.org/api-guide/serializers/#modelserializer.
In your case you probably need to use nested serialization and make the serialization of the object field smart (that field can contain references to different kind of objects).
There is an open issue about this on Github: https://github.com/GetStream/stream-django/issues/38. Ideally this is something the library will provide as helper/example, so any code contribution / input will help making that happen.

Related

DjangoREST: Extracting value from POST request to use in overridden create method

I am trying to accomplish a simple task of extracting the value passed from the POST request and using it as a parameter inside the overridden create method.
This is the example POST request body JSON, and "documented" is the field I wish to extract.
### POST
{
"url": "aaaa",
"title": "bbbb",
"publisher": "bbbb",
"desc": "bbbb",
"summary": "bbbb",
"documentId": "onDKe6K"
}
Using validated_data.pop("documentId") was the most obvious choice. However, I need DocumentListingField set to read_only=False in order to use this method. And that option raised larger issues as my Document model has an Hashfield that is not easily serializable.
Is there any other way to accomplish what I want in this situation? I've tried all of these but they all failed with "KeyError: documented"
validated_data.get("documentId")
validated_data["documentId"]
serializers.py
from django.forms.models import model_to_dict
class DocumentListingField(serializers.RelatedField):
def to_representation(self, instance):
return model_to_dict(instance.document)
class MySourceSerializer(serializers.ModelSerializer):
Document = DocumentListingField(many=False, read_only=True)
class Meta:
model = MySource
fields = (
"id",
"url",
"title",
"publisher",
"desc",
"summary",
"Document",
)
def create(self, validated_data):
documentId = validated_data.get("documentId"). <========= LINE OF INTEREST
print(documentId)
source = MySource.objects.create(
document=Document.objects.get(id=documentId), **validated_data
)
print(validated_data)
source.save()
return source
I think you can set the documentId field in the serializer.
class MySourceSerializer(serializers.ModelSerializer):
Document = DocumentListingField(many=False, read_only=True)
documentId = serializers.CharField(write_only = True)
lass Meta:
model = MySource
fields = (
...
"documentId",
)

Handle complex request formats and return response

I am building an API using Django rest framework. My API has to receive complex requests that are somewhat different from my models. More specifically the request has to include fields that do not exist in my models.
As an example I have included one of the models and the request that will be received by the API.
from django.db import model
class Author(models.Model):
first_name = models.CharField(max_length=9, blank=False)
last_name = models.CharField(max_length=9, blank=False)
birth_year = mmodels.CharField(max_length=9, blank=False)
and the json request is
{
"general": {
"name": "John",
"surname": "Doe"
},
"details": [
"1980"
]
}
How can I parse that request efficiently, store the data in my database and finally return a response similar to the request?
My approach so far is to create a serializer like the following and modify its create() and to_represent() methods, however this approach seems very dirty especially with nested relationships.
class AuthorSerializer(serializers.ModelSerializer):
general = serializers.DictField(write_only=True)
details = serializers.ListField(write_only=True)
class Meta:
model = Author
fields = [
"id", "general", "details",
]
def create(self, validated_data):
author_data = {}
author_data['first_name'] = validated_data['general']['name']
author_data['last_name'] = validated_data['general']['surname']
author_data['birth_year'] = validated_data['details'][0]
author = Author.objects.create(**author_data)
return author_data
def to_representation(self, instance):
final_representation = OrderedDict()
final_representation["id"] = instance.id
final_representation["general"] = {}
final_representation["general"]["name"] = instance.first_name
final_representation["general"]["surname"] = instance.last_name
final_representation["details"] = [instance.birth_year]
return final_representation

Design pattern for DRY approach to dynamic serializer fields

Basically, what I want to achieve is to make the list of fields in a serializer be optionally dynamic depending on whether the user has provided the list of fields they are interested in.
Here's my serializer for DRF serializer:
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
fields = self.context['request'].query_params.get('fields')
if fields:
fields = fields.split(',')
allowed = set(fields)
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
And my serializer:
class MySerializer(serializer_mixins.DynamicFieldsModelSerializer, serializers.ModelSerializer):
# fields...
This achieves the goal of not including the fields that the user has not mentioned in fields param of the queryset. But! We end up with actual query to the database that fetches the entire set of fields. This issue, in turn, could be solved by just adding the following code to the view:
class Rfs(ListAPIView):
serializer_class = MySerializer
def get_queryset(self):
qs = ...
fields = request.query_params.get('fields')
if fields:
qs = qs.only(*fields.split(','))
return qs
However, fills like two issues issues here:
non-DRY pattern since we have to repeat ourselves both in the view and the serializer
Sometimes it might be the case that the field name inside the queryset does not correspond exactly to the field name of the model.
So maybe there's some more elegant and Django-native solution for this usecase ?
I am using drf_queryfields
In dependence of your query_params your view will be modified
GET http://127.0.0.1:8000/snippets/
[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
},
{
"id": 2,
"title": "",
"code": "print \"hello, world\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
}
]
GET http://127.0.0.1:8000/snippets/?fields=id,code
[
{
"id": 1,
"code": "foo = \"bar\"\n",
},
{
"id": 2,
"code": "print \"hello, world\"\n",
}
]
I hope that´s it what you would like to achieve.

Django-notifications serialize target rest framework

I'm trying to add Django-notifications to my drf project. I get response when hitting the endpoint:
[
{
"recipient": {
"id": 274,
"username": "harry",
"first_name": "Harry",
"last_name": "Moreno"
},
"unread": true,
"target": null,
"verb": "invite approved"
}
]
serializers.py
class GenericNotificationRelatedField(serializers.RelatedField):
User = get_user_model()
def to_representation(self, value):
if isinstance(value, Invite):
serializer = InviteSerializer(value)
if isinstance(value, User):
serializer = UserSerializer(value)
return serializer.data
class NotificationSerializer(serializers.Serializer):
recipient = UserSerializer(read_only=True)
unread = serializers.BooleanField(read_only=True)
target = GenericNotificationRelatedField(read_only=True)
How do I make the target non-null?
Turns out the target is null because that is how I created the notification in the model
notify.send(user, recipient=user, verb='you reached level 10')
if I wanted a non-null target I should specify one like
notify.send(user, recipient=user, target=user, verb='you reached level 10')
Note: there is no django view that generates the json in the question.
In our urls.py we wire up the route to the notification view from the app.
path(
"alerts/",
views.NotificationViewSet.as_view({"get": "list"}),
name="notifications",
),
see the installation instructions https://github.com/django-notifications/django-notifications#installation

Nested Image Field in custom Page representation wagtail api

We are building a headless CMS with the wagtail API.
Our main model became very long, to make the representation cleaner and more easily accessible for the Frontend,
I am trying to group the different fields of my PageModel into sections.
But I don't manage to serialize the nested ImageField.
This is my PageModel:
class LandingPage(Page):
…
introduction_headline= models.CharField()
introduction_text = RichTextField()
introduction_icon = models.ForeignKey(
'main.CaptionImage',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name = '+',
)
…
I would like to group those fields into one section in the api, like so:
{
"id": 3,
"meta": {…},
"introduction_section": {
"introduction_headline": "intro head",
"introduction_text": "<p>intro text</p>",
"introduction_image": {
"id": 1,
"meta": {
"type": "main.CaptionImage",
"detail_url": "http://localhost/api/v2/images/1/",
"download_url": "/media/original_images/1.png"
},
"title": "german_design_image.png",
"caption": "Pretty Image"
},
},…
I managed to accomplish this in parts by writing a custom IntroductionSection - serializer:
class LandingPage(Page):
…
api_fields = [
APIField('introduction_section', serializer=IntroductionSectionField(source='*')),
…
]
class IntroductionSectionField(Field):
read_only = True
write_only = False
def to_representation(self, value):
return {
"introduction_headline" : value.introduction_headline,
"introduction_text" : value.introduction_text,
"introduction_image" : ?
}
But I simply can't figure out how to serialize the nested Image Field?
I want the same representation as the standard nested-relation-representation of the page model.
I tried around with get_related_field() method of the PageModel, tried to call the ImageSerializer, and all sorts of other things.

Resources