码迷,mamicode.com
首页 > 其他好文 > 详细

django rest framework 外键序列化方法与问题总结

时间:2020-06-24 19:26:09      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:操作   roo   序列   album   erro   track   length   service   原来   

 

为前端提供数据时,往往是这样的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)
就搞定了。。

官网例子里有,但是很容易忽略,这里提出来,希望大家注意

 

django rest framework 外键序列化方法与问题总结

标签:操作   roo   序列   album   erro   track   length   service   原来   

原文地址:https://www.cnblogs.com/ellisonzhang/p/13189207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!