Reputation: 244
Referring to the Django Rest Framework tutorial app:
https://github.com/tomchristie/rest-framework-tutorial
Referring to the users page, that is:
domain/port/snippets/users/
The response is as follows, in my case:
HTTP 200 OK
Vary: Accept
Content-Type: text/html; charset=utf-8
Allow: GET, HEAD, OPTIONS
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"url": "domain/port/snippets/users/1/",
"username": "super",
"snippets": [
"domain/port/snippets/1/",
"domain/port/snippets/3/"
]
},
{
"url": "domain/port/snippets/users/2/",
"username": "super2",
"snippets": [
"domain/port/snippets/4/"
]
}
]
}
What I have been trying to do is to somehow replace the "snippets" list with a single URL that links to a page for user1_snippets in the case of the first user and to a page for user2's snippets in the case of user 2...
By "snippets list", I'm referring to this chunk of text (which could be long) : "snippets": [ "domain/port/snippets/1/", "domain/port/snippets/3/" ]
So I just need to get the framework to produce something like the following code:
<a href="domain:port/snippets/user/1">snippets</a>
<a href="domain:port/snippets/user/2">snippets</a>
Then it will be really easy to develop the matching url conf and view.
The reason I want to do this is that in my own app, my analogous 'snippets' are very large in number, so I think it would be sensible to group them - on a separate page - for one (analogous) user. Then I can have the "user" page just for discovery of users. It will be quick to load, easy to interpret etc.
I know the answer lies in the documentation below, and I'll get there eventually but a few pointers would be really helpful.
http://django-rest-framework.org/api-guide/relations.html
Much appreciated,
Upvotes: 1
Views: 1218
Reputation: 2665
There is a section on so called "Hyperlinking" in the tutorial:
http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis.html
and as you said, you need to look for HyperlinkedIdentityField
in the relations article.
So your serializer could look like this:
class HyperlinkedSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedIdentityField(view_name='snippet-list')
class Meta:
model = User
fields = ('snippets')
Then the url is resolved using the provided 'snippet-list' view_name.
Hope this helps.
Upvotes: 1