I have a React application where I'm using Django+REST for the API and backend. On the frontend, I send a POST request to create a Job
model and run the job. In the response, I retrieve the ID of the new Job
object.
axios.post('http://127.0.0.1:8000/api/jobs/', query)
.then((resp) => {
setActiveJobs([...activeJobs, resp.data.id])
}, (error) => {
console.log(error)
})
When the job finishes running, it creates multiple Result
objects associated to it by a ForeignKey. These are my two models:
class Job(models.Model):
query = models.CharField(max_length=255, blank=True, null=True)
status = models.CharField(max_length=10, blank=True, null=True)
class Result(models.Model):
job = models.ForeignKey(Job, blank=False, null=False, on_delete=models.CASCADE)
result_no = models.IntegerField(blank=False, null=False)
... more fields
I'm having trouble using rest_framework in Django to send a GET request using the Job
's ID to get a list of all the Result
associated with it. I've tried to give custom implementations for retrieve(self, request, pk=None)
and get_queryset(self)
but so far my approaches have not worked. Ideally, I'd like to call a url such as localhost:8000/api/results/15
where 15
would be the object id of the Job
that was created. If there are 5 Result
objects that have the job
ForeignKey field set as the Job
object with an ID of 15
, a list of those 5 Result
s would be returned in the response.
My parsed-down views.py and urls.py are below:
views.py
class ResultsView(viewsets.ModelViewSet):
serializer_class = ResultSerializer
queryset = Result.objects.all()
# one potential solution could be along the lines of this? Does not work tho
def get_queryset(self):
job_id = self.kwargs['pk']
queryset = self.queryset.filter(job = job_id)
return queryset
urls.py
router = routers.DefaultRouter()
router.register(r'results', views.ResultsView, 'my_project')
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
# re_path('^api/results/(?P<job>.+)/$', views.ResultsView),
]
I think there may be an issue with attempting to match an integer ID to a ForeignKey field that is an object, but when I view localhost:8000/api/results/
I am able to see an object where the ForeignKey field job
is listed as a plain integer.
Is there an appropriate pattern for a task like this?