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.
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()
- How do I use perform_create to set a field automatically in Django Rest Framework?
- How should multiple Django apps communicate with each other?
- Is there a way to generate pdf containing non-ascii symbols with pisa from django template?