Arik
Arik

Reputation: 71

Django basic models logic

Looking for a way to create a model with a lot of tasks, each task is boolean ('Completed', 'Uncompleted'), and also it's own uniqe timestamp.

class project(models.Model):
  task1 = models.BooleanField()
  task1date = models.DateTimeField()
[...]

It's don't make amy sence to me, since there will be a lot to tasks. Every task has it's own title, the title stay the same for every single project (A list of tasks, if you will), but i need an sperate timestamp for the time the task have completed on the speacific project. What am i missing?

Upvotes: 1

Views: 91

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You make an extra model Task with three fields competed, timestamp, and a ForeignKey to Project:

class Task(models.Model):
    completed = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    project = models.ForeignKey(Project, related_name='tasks', on_delete=models.CASCADE)

So here a Task will refer to a Project. You can make as many Tasks as you want that you relate to a given Project. For example with:

Task.objects.create(project=my_project)

where my_project is a Project object.

You can access the set of related Task objects of a Project with:

myproject.tasks.all()

For more information, see the many-to-one relations section of the documentation.

Note: normally a Django models, just like all classes in Python are given a name in PerlCase, not snake_case, so it should be: Project instead of project.

Upvotes: 2

Related Questions