I created nested serialization but it is return only project name from project model but I want to return list of ids for one project. Here you can find create nested serialization Created nested serialization
class Project(models.Model):
project_id = models.AutoField(primary_key=True, unique=True)
project_name = models.CharField(max_length=100)
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 Assignment(models.Model):
assignment_id = models.AutoField(primary_key=True)
assignment_name = models.CharField(max_length=150)
site_id = models.ForeignKey(ProjectSite,related_name="projectsiteidkey", on_delete=models.CASCADE)
assigned_to_id = models.ForeignKey('auth.User',related_name="assignedtoidfkey",on_delete=models.CASCADE)
CodePudding user response:
I think you can use the SerializerMethodField
to get those value.
class YourSerializer(serializers.ModelSerializer):
...
site_ids = serializers.SerializerMethodField(read_only = True)
...
def get_site_ids(self, obj):
return list(obj.projectid.values_list('id').distinct())