本文由Scarb发表于金甲虫的博客,转载请注明出处

DRF 在序列化器中显示关联表的额外域值

需求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# models.py
from django.db import models

class Member(models.Model):
name = models.CharField(max_length = 20)
groups = models.ManyToManyField('Group', through = 'Membership')

class Group(models.Model):
name = models.CharField(max_length = 20)

class Membership(models.Model):
member = models.ForeignKey('Member')
group = models.ForeignKey('Group')
join_date = models.DateTimeField()

需要将join_date在GroupList中显示出来

最终访问Member时希望收到的返回结果是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
'id' : 2,
'name' : 'some member',
'groups' : [
{
'id' : 55,
'name' : 'group 1'
'join_date' : 34151564
},
{
'id' : 56,
'name' : 'group 2'
'join_date' : 11200299
}
]
}

解决方法

MemberSerializer中定义

1
groups = MembershipSerializer(source='membership_set', many=True)

然后MembershipSerializer可以这样定义

1
2
3
4
5
6
7
8
9
class MembershipSerializer(serializers.HyperlinkedModelSerializer):

id = serializers.ReadOnlyField(source='group.id')
name = serializers.ReadOnlyField(source='group.name')

class Meta:
model = Membership

fields = ('id', 'name', 'join_date', )

通过序列化group下的关联关系membership_set实现join_date的显示

参考资料

  1. include-intermediary-through-model-in-responses-in-django-rest-framework
  2. how-to-work-with-manytomanyfield-with-through-relation-in-django-rest-framework