如何在DRF的父序列化器中获取和显示所有子对象

时间:2018-12-07 11:54:44

标签: django-rest-framework foreign-keys django-generic-views django-serializer

对于父对象和子对象的3种不同视图,我有3种不同的序列化器。这些视图是CreateAPIView,ListAPIView,RetrieveAPIView。因此,我的CreateAPIView有一个用于创建对象的序列化程序,ListAPIView有一个用于列出对象的序列化程序,而RetrieveAPIView有一个用于显示对象详细信息的序列化程序。这对于子对象和父对象都是如此。如何列出父对象中与其相关的所有子对象? 这意味着在父级的RetrieveAPIView中,我要显示其子级的ListAPIView。

型号:

Class Boards(models.Model)

user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=50, blank=False, null=False, unique=True)
slug = models.SlugField()

def __str__(self):
    return self.name

def save(self, *args, **kwargs):
    self.slug = slugify(self.name)
    super(Boards, self).save(*args, **kwargs)

类列表(models.Model):

name = models.CharField(max_length=50, blank=False, null=False, unique=True)
slug = models.SlugField()
board = models.ForeignKey(Boards, on_delete=models.CASCADE)

def __str__(self):
    return self.name

def save(self, *args, **kwargs):
    self.slug = slugify(self.name)
    super(Lists, self).save(*args, **kwargs)

和序列化器: 类BoardCreateSerializer(ModelSerializer):

# user = request.user
class Meta:
    model = Boards
    fields = ['name']

BoardListSerializer类(ModelSerializer):

url = HyperlinkedIdentityField(
    view_name = 'trello:board-detail',
    lookup_field = 'slug',
)
user = SerializerMethodField()

class Meta:
    model = Boards
    fields = ['url', 'name', 'user']

def get_user(self, obj):
    return str(obj.user.username)

BoardDetailSerializer(ModelSerializer)类:

user = SerializerMethodField()

class Meta:
    model = Boards
    fields = ['id', 'name', 'user']

def get_user(self, obj):
    return str(obj.user.username)

类似地,我也有列表的序列化程序。(boards-父对象,lists-children)。如何在与之相关的委员会的详细信息视图中显示所有列表?

1 个答案:

答案 0 :(得分:1)

您可以通过不同的方式执行此操作:

  1. 使用source自变量,方法是将此字段添加到BoardDetailSerializer

    class BoardDetailSerializer(ModelSerializer):
        user = SerializerMethodField()
        lists = ListSerializer(
            source='Lists_set',
            many=True
        )
        class Meta:
            model = Boards
            fields = ['id', 'name', 'user', 'lists']
    
        def get_user(self, obj):
            return str(obj.user.username)
    
  2. 您也可以像对用户一样使用SerializerMethodField()。在该方法中,您需要将列表传递给序列化程序,并获取将采用json格式的数据(假设您使用的是默认的json渲染器)