[Fixed]-Model Method from rest_framework modelSerializer

19👍

For your first question source attribute is the answer, citing:

May be a method that only takes a self argument, such as
URLField(‘get_absolute_url’)

For your second answer, yes it is also possible. Check the example it provides in their docs: http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields

PS: I really love drf for its very complete documentation =).

EDIT

To use the source attribute you can just declare a new explicit field like so:

is_project = serializers.BooleanField(source='is_project')

With this, is_project field has the value of the is_project method of your instance. Having this, when creating the dynamic serializer (by modifying its init method) you can add the ‘project’ field if it’s True.

👤argaen

5👍

@argaen is absolutely right, source is a DRF core argument, and would most definitely solve your problem. However, it’s redundant to use source, if the field name is the same as the source. So the above answer won’t require you specify source, since field name is_project is the same as source name is_project.

So in your case:

is_project = serializers.BooleanField()

Leave a comment