Tomas
Tomas

Reputation: 59

Putting methods in a class in views.py

I am creating a simple todo app just to learn Python & Django. My current code:

def create_task(request):
    # code for creating a task

def delete_task(request, task_id):
    # code for deleting task

def show(request, task_id):
    # show a task

def list(request):
    # show list of tasks

def create_sub_task(request):
    # code for creating a sub_task

def delete_sub_task(request, sub_task_id):
    # code for deleting sub_task

def flip_sub_task_completed(request, sub_task_id)
    # make a sub_task completed/uncompleted

As you can see, a task has subtasks. This is working fine. But I think it would be better to separate Tasks and SubTasks, and create 2 classes for them. Would it be better? And how would I go on achieving that? How would I need to change my urlpatterns = [ to make it work? Thanks a lot!

edit: models.py:

class Task(models.Model):
    description = models.CharField(max_length=250)
    user = models.ForeignKey(User, on_delete=models.CASCADE)


class SubTask(models.Model):
    description = models.CharField(max_length=250)
    completed = models.BooleanField(default=False)
    task = models.ForeignKey(Task, on_delete=models.CASCADE)

Upvotes: 0

Views: 45

Answers (1)

AKX
AKX

Reputation: 169416

It's probably not better to create a separate model for SubTasks – instead add a parent foreign key to your Task model; tasks with parents are subtasks:

class Task(models.Model):
    # ...
    parent = models.ForeignKey('self', related_name='subtasks')

If you need a multi-level hierarchy, I suggest looking into Django-Treebeard or Django-MPTT, which can be used for efficient modeling of trees in Django models.

Upvotes: 1

Related Questions