Home > front end >  Need to return the value of a foreign key ID in a different model using django rest framework
Need to return the value of a foreign key ID in a different model using django rest framework

Time:03-16

models.py

class Project(models.Model):
    
    project_name = models.CharField(max_length=20)
    client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None)
    user=models.ManyToManyField(Default_User,related_name='users',default=None)
    description=models.TextField()
    type=models.TextField() 

class Meta:
        
        db_table ='Project'
    
    
    def __str__(self):
        return self.project_name   

class Job(models.Model):
    
    job_name=models.CharField(max_length=50)
    user= models.ForeignKey(Default_User,on_delete=CASCADE)
    project = ChainedForeignKey(Project,chained_field="user", chained_model_field="user",related_name='projects',show_all=False, auto_choose=True, sort=True)
    date = models.DateField(max_length=10,default=None)   

class Meta:
        
        db_table ='Job'
    
    def __str__(self):
        return '{}'.format(self.job_name)

Serializers

class ProjectSerializers(serializers.ModelSerializer):
    
    class Meta:
      
        model= Project
        fields= '__all__'

class Job_Serializers(serializers.ModelSerializer):

    class Meta:
      
        model= Job
        fields = '__all__'

viewsets

class ProjectViewSet(viewsets.ModelViewSet):
    authentication_classes =[JWTAuthentication] 
    permission_classes=(permissions.IsAdminUser,)
    queryset=models.Project.objects.all()
    serializer_class=serializers.ProjectSerializers
    filter_backends = [filters.SearchFilter]
    search_fields = ['project_name']

class Job_Viewset(viewsets.ModelViewSet):
    renderer_classes = (CustomRenderer, )
    authentication_classes =[JWTAuthentication] 
    permission_classes=(permissions.IsAdminUser,)
    queryset=models.Job.objects.all().order_by('-id')
    serializer_class=serializers.Job_Serializers

Actually I need to get the project name from the Project model in the Job model. As now as project is a foreign key in Job model it is returning the project_id in the Job model but i need to get the project name along with the id in the job model response. I have tried with the queryset but i couldn't able to get the results which i expected. Need to get ike below results while using get call function.

Result expected:
{
            "id": 1,
            "job_name": "API for Timesheet",
            "date": "2022-03-08",
            "user": 2,
            "project": 1,
            "project_name": timesheet #need to get like this
        }

CodePudding user response:

You should change Job_Serializers :

class Job_Serializers(serializers.ModelSerializer):

    project = ProjectSerializers()
    class Meta:
      
        model= Job
        fields = '__all__'

The result will be:

{
            "id": 1,
            "job_name": "API for Timesheet",
            "date": "2022-03-08",
            "user": 2,
            "project": { "id": 1,
                         "project_name": timesheet #need to get like this,
                          ...
                        }
            
        }

Or You can add some fields on the Job_Serializers:

class Job_Serializers(serializers.ModelSerializer):

    project_name = serializers.CharField(source='project.project_name')
    class Meta:
      
        model= Job
        fields = ['job_name', 'id', 'date', 'user', 'project', 'project_name']

The result should be

{
            "id": 1,
            "job_name": "API for Timesheet",
            "date": "2022-03-08",
            "user": 2,
            "project": 1,
            "project_name": timesheet #need to get like this
        }


Finally it should better change Job_Serializers to JobSerializers.

  • Related