i'm working on a django project that manages some projects. In a view I have to show only the projects of the logged in user, but everything i do doesn't work and i really don't know what else to try. I'm new to programming.
Basically my application has a Worker Model that has only a field: worker = models.ForeignKey(User)
Then it has a Responsable Model that has only one field: responsable = models.ForeignKey(User) I have these 2 models because i need to separate the users in workers and responsables.
This is my project Model:
class Project(models.Model):
title = models.CharField(max_length=255)
description = models.CharField(max_length=1000)
client = models.ForeignKey(Cliente, on_delete=models.CASCADE)
complete = models.BooleanField(default=False)
urgent = models.BooleanField(default=False)
deadline = models.DateField()
worker = models.ForeignKey(Worker, on_delete=models.CASCADE)
responsable = models.ForeignKey(Responsable, on_delete=models.CASCADE)
This is in my views.py:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Project
@login_required(login_url='/accounts/login/')
def projectsWorkers(request):
user = request.user
user_projects = Project.objects.filter(worker=user).order_by('deadline')
template = 'projects/projects-worker-home.html'
return render(request, template, {'user_projects': user_projects, 'user': user})
but i get an error: Cannot query "Simone": Must be "Worker" instance.
I think that the problem is the fact that in my Project Model the worker field has a foreign key to Worker and not to User, but i can't change that, so what should i do?
Based on the comment
Basically my application has a Worker Model that has only a field:
worker = models.ForeignKey(User)
, you should access theworker
field of theWorker
model so:
user_projects = Project.objects.filter(worker__worker=user).order_by('deadline')
The first worker
thus follows the ForeignKey
from the Project
model to the Worker
model, and the second worker
from the Worker
model to the User
model.