简体   繁体   中英

How to create a model related to another to generate a list

I am trying to create a todolist where users can create a list of tasks like "morning routine" and import them directly into my todo app.

Models.py Todo and TodoList

class Todo(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur")
    text = models.CharField(max_length=150, verbose_name="Nom de la Todo")
    content = models.TextField(verbose_name="Description supplémentaire",null=True, blank=True)


class TodoList(models.Model):
    list = models.ForeignKey(Todo, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur")
    text = models.CharField(max_length=150, verbose_name="Nom de la Todo")

My todoApp is working but I cannot figure out how to link them and import the list from todo to TodoList

Thanks guys

If you added a ManyToManyField in place of the ForeignKey on TodoList's list attribute it may do what you need.

class Todo(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur")
    text = models.CharField(max_length=150, verbose_name="Nom de la Todo")
    content = models.TextField(verbose_name="Description supplémentaire",null=True, blank=True)


class TodoList(models.Model):
    list = models.ManyToManyField(Todo, verbose_name="Nom de l'utilisateur")
    text = models.CharField(max_length=150, verbose_name="Nom de la Todo")

Then in the logic of your app, you could do things like:

todolist1 = TodoList(text='Stuff to do before tonight')
toddolist1.save()

todo1 = Todo(author=author_obj, text="Brush teeth", content="Remember to floss")
todo1.save()
todo2 = Todo(author=author_obj, text="Comb hair", content="Use water")
todo2.save()

todolist1.todos.add(todo1, todo2)

Then you would get the list by doing:

todolist1.todos.all()

reference: https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/ where Article in that example is equivalent to TodoList , and Publication is equivalent to Todo .

EDIT: Removing an item from the TodoList would look like this:

todolist1.todos.remove(todo1)

.remove() won't delete a todo entirely, so todo1 would still appear in the other todolists. To totally remove a todo from all todolists, you'd do something like.

todo1.delete()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM