Django Rest Framework nested serializer not showing related data

前端 未结 1 540
轮回少年
轮回少年 2021-02-19 18:22

I have a basic setup using the Django Rest Framework. I have two models and a nested serializer setup:

# models.py

from django.db import models

class Plan(mod         


        
1条回答
  •  自闭症患者
    2021-02-19 19:06

    The problem comes from your queryset: queryset = Plan.objects.all(). None of the items in this queryset has .group attribute that's why your result is empty. By default Django creates a reverse relation of the plan ForeignKey called group_set (unless you don't rename it via related_name) (this means that every plan item in the queryset have a group_set attribute which is a queryset containing all the groups of this plan). You can use this attribute in order to get a proper serialization. This means to change:

    class PlanSerializer(serializers.ModelSerializer):
        group_set = GroupSerializer(many=True, read_only=True)
    
        class Meta:
            model = Plan
            fields = ('name', 'group_set')
    

    If you really want to stick with group (btw this is a very bad name for a list of groups). You can hack it with prefetch_related like so:

    queryset = Plan.objects.prefetch_related('group_set', to_attr='group')
    

    this way every plan item will have a group attribute - a queryset containing all the groups for this plan.

    0 讨论(0)
提交回复
热议问题