Home > Back-end >  How do I use foreign key in django to have item sets?
How do I use foreign key in django to have item sets?

Time:11-14

Models.py

from django.db import models

# Create your models here.

class Project_types(models.Model):
    project_type = models.CharField(max_length=200)

    def __str__(self):
        return self.project_type

class Projects(models.Model):
    project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE)
    project = models.CharField(max_length=200)

    def __str__(self):
        return self.project


class SourceCode(models.Model):
    project = models.ForeignKey(Projects, on_delete=models.CASCADE)
    source_code = models.CharField(max_length=99999)

    def __str__(self):
        return self.source_code

Views.py

from django.shortcuts import render
from .models import Project_types, Projects


def homepage(response):
    data = Project_types.objects.all()
    return render(response, 'main/homepage.html', {'project_types': data})


def hacks(response):
   return render(response, 'main/hacks.html', {'hacking_projects':"n"})

def games(response):
    type = Project_types(project_type='games')
    t = type.projects_set.all()
    return render(response, 'main/games.html', {'gaming_projects': t})

main/games.html

<!DOCTYPE html>

<html>
<head>
    <title>My Gaming Projects</title>
</head>
<body>
<header>My Gaming Projects</header>

<p>{{gaming_projects}}</p>
</body>

</html>

The problem is when I go into my django admin I clearly have a project by the name of "gaming project" under the project type 'games'. However when displaying it on my site it just shows a empty query. enter image description here

CodePudding user response:

This line:

type = Project_types(project_type='games') 

Needs to be:

type = Project_types.objects.get(project_type='games')
  • Related