321π
I think SerializerMethodField
is what youβre looking for:
class FooSerializer(serializers.ModelSerializer):
my_field = serializers.SerializerMethodField('is_named_bar')
def is_named_bar(self, foo):
return foo.name == "bar"
class Meta:
model = Foo
fields = ('id', 'name', 'my_field')
http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
58π
You can change your model method to property and use it in serializer with this approach.
class Foo(models.Model):
. . .
@property
def my_field(self):
return stuff
. . .
class FooSerializer(ModelSerializer):
my_field = serializers.ReadOnlyField(source='my_field')
class Meta:
model = Foo
fields = ('my_field',)
Edit: With recent versions of rest framework (I tried 3.3.3), you donβt need to change to property. Model method will just work fine.
- [Django]-ImportError: Failed to import test module:
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."
- [Django]-Django: Filter a Queryset made of unions not working
18π
if you want read and write on your extra field, you can use a new custom serializer, that extends serializers.Serializer, and use it like this
class ExtraFieldSerializer(serializers.Serializer):
def to_representation(self, instance):
# this would have the same as body as in a SerializerMethodField
return 'my logic here'
def to_internal_value(self, data):
# This must return a dictionary that will be used to
# update the caller's validation data, i.e. if the result
# produced should just be set back into the field that this
# serializer is set to, return the following:
return {
self.field_name: 'Any python object made with data: %s' % data
}
class MyModelSerializer(serializers.ModelSerializer):
my_extra_field = ExtraFieldSerializer(source='*')
class Meta:
model = MyModel
fields = ['id', 'my_extra_field']
i use this in related nested fields with some custom logic
- [Django]-Python Asyncio in Django View
- [Django]-Django-nonrel + Django-registration problem: unexpected keyword argument 'uidb36' when resetting password
- [Django]-How can I get tox and poetry to work together to support testing multiple versions of a Python dependency?
16π
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. No need for @property
and source='field'
raise an error.
class Foo(models.Model):
. . .
def foo(self):
return 'stuff'
. . .
class FooSerializer(ModelSerializer):
foo = serializers.ReadOnlyField()
class Meta:
model = Foo
fields = ('foo',)
- [Django]-How do you configure Django to send mail through Postfix?
- [Django]-Django.contrib.auth.logout in Django
- [Django]-Whats the difference between using {{STATIC_URL}} and {% static %}
12π
My response to a similar question (here) might be useful.
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]-Django development server reload takes too long
- [Django]-Django substr / substring in templates
- [Django]-Find object in list that has attribute equal to some value (that meets any condition)
10π
If you want to add field dynamically for each object u can use to_represention.
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = ('id', 'name',)
def to_representation(self, instance):
representation = super().to_representation(instance)
if instance.name!='': #condition
representation['email']=instance.name+"@xyz.com"#adding key and value
representation['currency']=instance.task.profile.currency #adding key and value some other relation field
return representation
return representation
In this way you can add key and value for each obj dynamically
hope u like it
- [Django]-Separation of business logic and data access in django
- [Django]-Django datetime issues (default=datetime.now())
- [Django]-How to resize the new uploaded images using PIL before saving?
5π
This worked for me.
If we want to just add an additional field in ModelSerializer
, we can
do it like below, and also the field can be assigned some val after
some calculations of lookup. Or in some cases, if we want to send the
parameters in API response.
In model.py
class Foo(models.Model):
"""Model Foo"""
name = models.CharField(max_length=30, help_text="Customer Name")
In serializer.py
class FooSerializer(serializers.ModelSerializer):
retrieved_time = serializers.SerializerMethodField()
@classmethod
def get_retrieved_time(self, object):
"""getter method to add field retrieved_time"""
return None
class Meta:
model = Foo
fields = ('id', 'name', 'retrieved_time ')
Hope this could help someone.
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-Django: How to format a DateField's date representation?
- [Django]-Stack trace from manage.py runserver not appearing
3π
class Demo(models.Model):
...
@property
def property_name(self):
...
If you want to use the same property name:
class DemoSerializer(serializers.ModelSerializer):
property_name = serializers.ReadOnlyField()
class Meta:
model = Product
fields = '__all__' # or you can choose your own fields
If you want to use different property name, just change this:
new_property_name = serializers.ReadOnlyField(source='property_name')
- [Django]-Django β How to pass several arguments to the url template tag
- [Django]-Add rich text format functionality to django TextField
- [Django]-How can I avoid "Using selector: EpollSelector" log message in Django?
2π
Even though, this is not what author has wanted, it still can be considered useful for people here:
If you are using .save()
ModelSerializerβs method, you can pass **kwargs
into it. By this, you can save multiple dynamic values.
i.e. .save(**{'foo':'bar', 'lorem':'ipsum'})
- [Django]-Filtering using viewsets in django rest framework
- [Django]-Are sessions needed for python-social-auth
- [Django]-Django β Rotating File Handler stuck when file is equal to maxBytes
0π
As Chemical Programer said in this comment, in latest DRF you can just do it like this:
class FooSerializer(serializers.ModelSerializer):
extra_field = serializers.SerializerMethodField()
def get_extra_field(self, foo_instance):
return foo_instance.a + foo_instance.b
class Meta:
model = Foo
fields = ('extra_field', ...)
- [Django]-Django, Turbo Gears, Web2Py, which is better for what?
- [Django]-Django F() division β How to avoid rounding off
- [Django]-How to server HTTP/2 Protocol with django
0π
Add the following in serializer class:
def to_representation(self, instance):
representation = super().to_representation(instance)
representation['package_id'] = "custom value"
return representation
- [Django]-ImportError: Failed to import test module:
- [Django]-Django connection to postgres by docker-compose
- [Django]-Django Framework β Is there a shutdown event that can be subscribed to?