1👍
✅
This is my current fix. I am open to another approach that works cleaner with model_to_dict()
@property
def thumbnail_url(self):
return self.thumbnail.url
def toJSON(self):
return {
**model_to_dict(self, fields=['all', 'my', 'fields']),
**{'thumbnail_url': self.thumbnail_url }
}
2👍
You would want a serializer instead, it might be cleaner instead of model_to_dict()
https://www.django-rest-framework.org/api-guide/serializers/
This is what the serializer class would look like:
from rest_framework import serializers
from .people import Person # replace with where your Person model is at.
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = [
'all',
'your',
'fields',
'thumbnail_url'
]
And instead of model_to_dict(self, fields=['all', 'my', 'fields']),
:
from rest_framework.response import Response
from people.models import Person
from people.serializers import PersonSerializer
...
instance = Person.objects.all().first() # Getting first person for the example
if instance:
data = PersonSerializer(instance).data
return Response(data)
- [Django]-Django-non rel and dbindexer ordering property
- [Django]-How can I use RESTful services with Django + Mongoengine?
- [Django]-How to redirect (including URL change) in Django?
Source:stackexchange.com