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


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

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

  • 相关阅读:
    【原创】Algorithms:原地归并排序
    Java中相等测试
    测试可变字符序列stringBuilder
    呃。。第一篇随笔。
    hiho兄弟的字典树之争(hiho1014)
    字典树
    最大公约数
    素数
    递归算法1
    logging模块,collections模块,random模块
  • 原文地址:https://www.cnblogs.com/ellisonzhang/p/13189207.html
Copyright © 2020-2023  润新知