model field named url and django rest framework url
It may be considered poor form (I am by no means a pro programmer or rest_framework expert), but I believe you can add extra context to the serialized output:
http://django-rest-framework.org/api-guide/serializers.html#specifying-fields-explicitly
class AccountSerializer(serializers.ModelSerializer):
url = serializers.CharField(source='get_absolute_url', read_only=True)
groups = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = Account
Extra fields can correspond to any property or callable on the model.
So in the above the field 'get_absolute_url' must be in the 'Account' model. In your case (I think) you could do this:
class ModelSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
url_in_model = serializer.Field(source='url')
class Meta:
model = Model
fields = ('url', 'url_in_model', 'owner', 'title', 'abstract', 'category', 'position', 'param1')
Of course you would pick the field type that suits.
I haven't had the chance to test this, so there is the chance that using 'url' as your source causes an issue and you may want to name your model field something else - apologies if that is the case and I have wasted your time.
Hope I have helped.
The accepted answer didn't work for me in DRF 3. I got my model's url
data for both url
and url_in_model
. To get the correct url
value from DRF, it looked like:
class AccountSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='account-detail')
url_in_model = serializer.URLField(source='url')
class Meta:
model = Account
account-detail
should be replaced with whatever view corresponds to a single Account.
I personally prefer to set the default hyperlinked field to another name altogether.
You can do this via the URL_FIELD_NAME
setting.
Source: http://www.django-rest-framework.org/api-guide/serializers/#changing-the-url-field-name
e.g: URL_FIELD_NAME = 'key'
(default is 'url')