MerrinX
MerrinX

Reputation: 183

django relation between classes

Let say you have a class Project that is own by a team. One team can have many projects, but only one team for each project.

class Project(models.Model):
    project_manager = models.ForeignKey(Profile, on_delete=CASCADE)

    title           = models.CharField(max_length=55, null=True, blank=True)
    developers      = models.ManyToManyField(Profile, related_name='projects')
    slug            = models.SlugField(max_length=500, unique=True, blank=True)
    description     = models.TextField(default="Project description")
    teams           = models.ForeignKey(Team, blank=True, null=True, on_delete=CASCADE)
    tasks = project.task_set.all()   <-- like this?

Then each project has a task, so have to create a task class with a foregin key to project

class Task(models.Model):
    title           = models.CharField(max_length=55, null=True, blank=True)
    members         = models.ManyToManyField(Profile, related_name='tasks')
    slug            = models.SlugField(max_length=500, unique=True, blank=True)
    task_completed  = models.BooleanField(default=False)
    description     = models.TextField(default="Task description")
    project         = models.ForeignKey(Project, blank=True, null=True, on_delete=CASCADE)

when then trying to get all the members from the task class, while being in a view for the project class, there is no relation, project does not have access, how do one make sure project knows of Tasks as Tasks knows of project?

Upvotes: 0

Views: 46

Answers (1)

Aur&#233;lien
Aur&#233;lien

Reputation: 1655

You can get your tasks with _set.all()

To access to your tasks based upon the project :

tasks = project.task_set.all()

Upvotes: 1

Related Questions