为前端提供数据时,往往是这样的json
{
'album_name': 'Undun',
'artist': 'The Roots',
'tracks': 01
}......
如果需要外键字段对应表的详细信息,像这样
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
...
],
}
要怎么配置?
查看 django rest framework 官网说明http://www.django-rest-framework.org/api-guide/relations/
虽然讲到了怎么操作,但是不详细,屡屡遇坑
所用到的model
class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ('album', 'order')
ordering = ['order']
def __unicode__(self):
return '%d: %s' % (self.order, self.title)
配置serializer
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('order', 'title', 'duration')
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
好像搞定了,运行起来才发现有个坑
Got AttributeError when attempting to get a value for field 'tracks' on serializer 'AlbumSerializer'
没有tracks字段,咋整?
原来只要在model foreignkey里面添加
related_name='tracks',
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
就搞定了。。
官网例子里有,但是很容易忽略,这里提出来,希望大家注意