67
You’re doing the right thing, except that CharField
(and the other typed fields) are for writable fields.
In this case you just want a simple read-only field, so instead just use:
customField = Field(source='get_absolute_url')
118
In fact there a solution without touching at all the model. You can use SerializerMethodField
which allow you to plug any method to your serializer.
class FooSerializer(ModelSerializer):
foo = serializers.SerializerMethodField()
def get_foo(self, obj):
return "Foo id: %i" % obj.pk
- [Django]-How do I get the object if it exists, or None if it does not exist in Django?
- [Django]-Handling race condition in model.save()
- [Django]-Django apps aren't loaded yet when using asgi
21
…for clarity, if you have a Model Method defined in the following way:
class MyModel(models.Model):
...
def model_method(self):
return "some_calculated_result"
You can add the result of calling said method to your serializer like so:
class MyModelSerializer(serializers.ModelSerializer):
model_method_field = serializers.CharField(source='model_method')
p.s. Since the custom field isn’t really a field in your model, you’ll usually want to make it read-only, like so:
class Meta:
model = MyModel
read_only_fields = (
'model_method_field',
)
- [Django]-How to set the timezone in Django
- [Django]-Default filter in Django model
- [Django]-Django Sitemaps and "normal" views
17
After reading all the answers here my conclusion is that it is impossible to do this cleanly. You have to play dirty and do something hadkish like creating a write_only field and then override the validate
and to_representation
methods. This is what worked for me:
class FooSerializer(ModelSerializer):
foo = CharField(write_only=True)
class Meta:
model = Foo
fields = ["foo", ...]
def validate(self, data):
foo = data.pop("foo", None)
# Do what you want with your value
return super().validate(data)
def to_representation(self, instance):
data = super().to_representation(instance)
data["foo"] = whatever_you_want
return data
- [Django]-How can I temporarily disable a foreign key constraint in MySQL?
- [Django]-Good open source django project for learning
- [Django]-Django Installed Apps Location
14
here answer for your question.
you should add to your model Account:
@property
def my_field(self):
return None
now you can use:
customField = CharField(source='my_field')
- [Django]-Django manage.py runserver invalid syntax
- [Django]-Django render_to_string missing information
- [Django]-How can I use the variables from "views.py" in JavasScript, "<script></script>" in a Django template?
13
To show self.author.full_name
, I got an error with Field
. It worked with ReadOnlyField
:
class CommentSerializer(serializers.HyperlinkedModelSerializer):
author_name = ReadOnlyField(source="author.full_name")
class Meta:
model = Comment
fields = ('url', 'content', 'author_name', 'author')
- [Django]-Django admin make a field read-only when modifying obj but required when adding new obj
- [Django]-Django Template Language: Using a for loop with else
- [Django]-Django Rest Framework Conditional Field on Serializer
10
I was looking for a solution for adding a writable custom field to a model serializer. I found this one, which has not been covered in the answers to this question.
It seems like you do indeed need to write your own simple Serializer.
class PassThroughSerializer(serializers.Field):
def to_representation(self, instance):
# This function is for the direction: Instance -> Dict
# If you only need this, use a ReadOnlyField, or SerializerField
return None
def to_internal_value(self, data):
# This function is for the direction: Dict -> Instance
# Here you can manipulate the data if you need to.
return data
Now you can use this Serializer to add custom fields to a ModelSerializer
class MyModelSerializer(serializers.ModelSerializer)
my_custom_field = PassThroughSerializer()
def create(self, validated_data):
# now the key 'my_custom_field' is available in validated_data
...
return instance
This also works, if the Model MyModel
actually has a property called my_custom_field
but you want to ignore its validators.
- [Django]-Paginating the results of a Django forms POST request
- [Django]-Delete multiple objects in django
- [Django]-UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)
8
With the last version of Django Rest Framework, you need to create a method in your model with the name of the field you want to add.
class Foo(models.Model):
. . .
def foo(self):
return 'stuff'
. . .
class FooSerializer(ModelSerializer):
foo = serializers.ReadOnlyField()
class Meta:
model = Foo
fields = ('foo',)
- [Django]-Data Mining in a Django/Postgres application
- [Django]-Python/Django: log to console under runserver, log to file under Apache
- [Django]-How do I convert a Django QuerySet into list of dicts?