model_to_dict() with a @property field is not being included

Question:

I am trying to include a field that is a property in the model_to_dict fields list.

class Person(models.Model):
    thumbnail = models.ImageField(upload_to='bla...')

    ...snipped...

    @property
    def thumbnail_url(self):
        return self.thumbnail.url

    def toJSON(self):
        return model_to_dict(self, fields=[..., 'thumbnail_url',...])

When I call Person.toJSON() it does not include thumbnail_url field.

What is wrong?

Thank you.

Asked By: kvothe__

||

Answers:

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 }
          }
Answered By: kvothe__

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)
Answered By: Gvistic
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.