ForeignKey Not returning linked data as expected
I have 2 models Project
and Fundamentals
the fundamentals is linked via FK to Project
I have a view that allows me to add data to the fundamentals
table and also a view to update the fundamentals
when data already exists.
But when I try to retrieve the data i pass is the project_id
in the request. But what seems to be happening is that if i have 5 projects and from project 5 i add fundamentals
data the data in the table has an ID of 1
being that this is the first entry in the fundamentals
table. but my project id is 5
being the 5th project
If i then go to project 1 and add fundamentals
it will return data from project 5.
I hope this makes sense?
I assume its the way i am requesting the data within these views:
def fundamentals_view(request, project_id):
check_exist = Fundamentals.objects.filter(project_name_id=project_id)
if check_exist:
return update_fundamentals_view(request, project_id)
else:
return add_fundamentals_view(request, project_id)
@login_required
def add_fundamentals_view(request, project_id):
project = get_object_or_404(Project, pk=project_id)
if request.method == 'POST':
form = FundamentalsForm(request.POST)
if form.is_valid():
fundamental = form.save(commit=False)
fundamental.project_name = project
fundamental.save()
return redirect('dashboard.html')
else:
form = FundamentalsForm()
return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form})
def update_fundamentals_view(request, project_id):
project = get_object_or_404(Fundamentals, pk=project_id)
form = FundamentalsForm(request.POST or None, instance=project)
if form.is_valid():
form.save()
return redirect('/')
return render(request, 'pages/update_fundamentals.html', {'project': project, "form": form})
Should I be sending in something else in the request, not project_id
Model
class Project(models.Model):
project_name = models.CharField(max_length=50, blank=False, unique=True)
project_website = models.URLField(max_length=50, blank=True)
project_description = models.TextField(blank=True)
def __str__(self):
return str(self.project_name)
class Fundamentals(models.Model):
Yes_No_Choices = [
('Yes', 'Yes'),
('No', 'No'),
('Unknown', 'Unknown')
]
Good_Bad_Choices = [
('Good', 'Good'),
('Bad', 'Bad'),
('Average', 'Average'),
('Unknown', 'Unknown')
]
project_name = models.ForeignKey(Project, on_delete=models.CASCADE)
project_roadmap = models.CharField(max_length=25, blank=True, choices=Yes_No_Choices)
project_tier_entry_level = models.CharField(max_length=25, blank=True, choices=Yes_No_Choices)
project_tier_entry_level_notes = models.CharField(max_length=25, blank=True)
def __str__(self):
return str(self.project_name