Last active
April 25, 2017 08:49
-
-
Save azpwnz/e1cd1465590cb8b482081e7e14330b95 to your computer and use it in GitHub Desktop.
ModelSerializer with custom fields (Django Rest Framework)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CampaignSerializer(serializers.ModelSerializer): | |
# companies is many-to-many field. Use StringRelatedField will show names of the companes instead of ids. | |
companies = serializers.StringRelatedField(many=True) | |
# format date | |
created_at = serializers.DateTimeField(format="%Y-%m-%d") | |
# custom field with count of companies (which is many-to-many field). It use method with the same name: get_<name of the field>(self, obj) | |
companies_count = serializers.SerializerMethodField() | |
def get_companies_count(self, obj): | |
return obj.companies.count() | |
class Meta: | |
model = Campaign | |
fields = ('id', 'name', 'description', 'status', 'companies', 'created_at', 'companies_count') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment