Basically I have models like this:
class Playlist(models.Model):
key = models.CharField(max_length=255,blank=True, unique=True)
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
pub_date = models.DateTimeField(auto_now_add=True)
videos = models.ManyToManyField(Video, through='PlaylistVideo')
class PlaylistVideo(models.Model):
playlist = models.ForeignKey(Playlist)
video = models.ForeignKey(Video)
position = models.IntegerField()
class Video(models.Model):
title = models.CharField(max_length=255,blank=True)
description = models.TextField(blank=True)
thumb = models.URLField(blank=True)
duration = models.IntegerField(default=0)
Now I want an API to return PLAYLISTS like this... But Videos should be sorted by POSITION in PlaylistVideo Model
{
"key": "h8x3",
"title": "First Playlist",
"pub_date": "2012-10-11T17:00:26Z",
"videos": [
{
....
},
{
....
}
]
},
How should I got about it?
Not too sure if you've managed to solve your issue, but I've came across this myself, and managed to make it work like by doing something like this:
create a custom serializer like this:
Here, I'm assuming you'd like to display all the fields under videos entity/table. Feel free to adjust to your needs/likings.
Then, all you need to do is this
Note: Always make sure that the source is referencing to the associative entity. Else you'd get a list of empty json.
Hope this would help anyone out there facing similar issue.
You can do it like this:
in serializers.py:
We need to add some documentation on 'through' relationships really.
In the meantime, this discussion may help:
https://groups.google.com/forum/#!topic/django-rest-framework/xzOhjILq3xA/discussion