Home > front end >  How to return only specified fields from serializerMethodField using DRF
How to return only specified fields from serializerMethodField using DRF

Time:06-10

It will return nested array like { project_name:test, site_id:[[1],[2]],site_name:[[test1],[test2]] },but I would like to return like this {{sitename:test1, siteid:1},{sitename:test2, siteid:2}}

class ProjectSite(models.Model):
    site_id = models.AutoField(primary_key=True, unique=True)
    site_name = models.CharField(max_length=200,name='project_site_name')
    project_id = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, 
    related_name="projectid")
class ProjectSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Project
        fields = '__all__'
class ProjectSiteSerializer(serializers.ModelSerializer):
  
    class Meta:
        model = ProjectSite
        fields = '__all__'
class Serializer(serializers.ModelSerializer):
    ...
    site_ids = serializers.SerializerMethodField(read_only = True)
    site_name = serializers.SerializerMethodField(read_only = True)
    
    ...

    def get_site_ids(self, obj):
        return list(obj.projectid.values_list('id').distinct())
    def get_site_name(self, obj):
        return list(obj.projectid.values_list('site_name').distinct())

CodePudding user response:

I think you can use the ProjectSerializer.

class ProjectSerializer(serializers.ModelSerializer):
    projectid = ProjectSiteSerializer(many = True, read_only = True)

    class Meta:
        model = Project
        fields = ('project_id', 'project_name', 'projectid',)
  • Related