我是使用DRF的新手。我有一个2层多对多的关系,我希望能够提供。
# models.py
class Person(models.Model):
name = models.CharField(max_length=32)
class Group(models.Model):
name = models.CharField(max_length=32)
people = models.ManyToManyField(Person,related_name='groups',blank=True)
class Event(models.Model):
name = models.CharField(max_length=32)
groups = models.ManyToManyField(Group,related_name='events',blank=True)
在我的序列化程序中,我希望能够在Person中显示他们正在参加哪个活动。
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ( 'id', 'name', 'groups' )
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ( 'id', 'name', 'people' )
class PersonSerializer(serializers.ModelSerializer):
groups = serializers.StringRelatedField(many=True)
#not sure how to lookup the events related field here...
events = EventSerializer(source='groups.name', many=True,read_only=True)
class Meta:
model = Person
fields = ( 'id', 'name', 'groups', 'events')
然而,当我查看事件时,我收到错误。这种查找甚至可能吗?
目前输出看起来像这样,我有组映射到事件“party”但它说'null':
{
"id": 1,
"name": "mike",
"groups": [
"dev"
],
"events": null
}
我希望输出成为事件列表。像这样:
{
"id": 1,
"name": "mike",
"groups": [
"dev"
],
"events": [
"party"
]
}
此外,我尝试过使用depth = 2,但它对很多领域都没有做任何事情。