Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-serializer

In django-rest-framework, I want to output the childdb in the same parentdb by putting the parentdb name in the url parameter


There is a model that binds the user with a foreignkey. What I want to do is set the url parameter to I'm writing an api that prints the items of children with the same parent when I put as_view/int:parentpk, but I can't implement it due to my lack of skills. Please help

Here is a model.py that accepts a user as a foreignkey

   class TestingTasks(models.Model): 
        Taskname = models.CharField(max_length=100, unique=True)    
        dateofuse = models.DateTimeField(auto_now_add=True)    
        Compressing = models.TextField()    
        Path = models.FileField(null=True)    
        parent_id = models.ForeignKey(User,related_name='users', on_delete=models.CASCADE,default=1)

And here is views.py

class TestingAPI(APIView):
permission_classes = [AllowAny]

def get(self, request, company_id):
    instance = TestingTasks.objects.filter(parent_id=id)
    serializer_class = TestingSerializer(instance)
    return Response(serializer_class.data)

Here is urls.py

path("Testing/<int:company_id>",views.TestingAPI.as_view())

I need to implement a total of three get, put, and delete, but I can't do the rest because I can't get. I'd appreciate it if you could give me a direction on how to do it. Have a nice day.


Solution

  • just add the functions in class

    class TestingAPI(APIView):
          permission_classes = [AllowAny]
    
          def get(self, request, company_id):
              instance = TestingTasks.objects.filter(parent_id=company_id)
              serializer_class = TestingSerializer(instance)
              return Response(serializer_class.data)
    
          def put(self, request, company_id):
              ...
          def delete(self, request, company_id):
              ...