Skip to content

Instantly share code, notes, and snippets.

@azpwnz
Last active April 25, 2017 08:49
Show Gist options
  • Save azpwnz/e1cd1465590cb8b482081e7e14330b95 to your computer and use it in GitHub Desktop.
Save azpwnz/e1cd1465590cb8b482081e7e14330b95 to your computer and use it in GitHub Desktop.
ModelSerializer with custom fields (Django Rest Framework)
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