Get parent from children in Django

Viewed 206

I have two models in my models.py:

class Case(model.Models):
    name = models.CharField(max_length=50)

class Work(model.Models):
    name = models.CharField(max_length=50)
    case = models.ForeignKey('Case', on_delete=models.CASCADE)

In my views.py I have function to update a work but also I need to access to its case to return to case template with POST:

def updateWork(request, pk):
work = Work(id=pk)
work_form = WorkForm(instance=work)
case = Work.objects.filter(...)

if request.method == 'POST':
    work_form = WorkForm(request.POST, instance=work)
    if work_form.is_valid():
        work_form.save()
        return redirect('update_case', pk='here should be the case id')

context = {'work_form': work_form, 'work': work}
return render(request, 'case/update_work.html', context)

How can I define the parent case id of the specific work to point it in line: return redirect('update_case', pk='here should be the case id') ?

1 Answers

You can access this through the .case attribute, or you can use .case_id to obtain the value for the column the ForeignKey refers to, which will be loaded when you need this:

def updateWork(request, pk):
    work = Work(id=pk)
    work_form = WorkForm(instance=work)
    case = Work.objects.filter(...)
    
    if request.method == 'POST':
        work_form = WorkForm(request.POST, instance=work)
        if work_form.is_valid():
            work_form.save()
            return redirect('update_case', pk=work.case_id)
    context = {'work_form': work_form, 'work': work, 'case': case}
    return render(request, 'case/update_work.html', context)
Related