[英]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. 我正在尝试创建一个todolist,用户可以在其中创建“早晨例程”等任务列表,并将它们直接导入我的todo应用程序。
Models.py Todo and TodoList Models.py Todo 和 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 我的todoApp正在工作,但我无法弄清楚如何链接它们并将列表从待办事项导入TodoList
Thanks guys 多谢你们
If you added a ManyToManyField in place of the ForeignKey on TodoList's list
attribute it may do what you need. 如果您在TodoList的
list
属性中添加了ManyToManyField来代替ForeignKey,它可能会执行您所需的操作。
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
. 参考: https :
TodoList
其中该示例中的Article
等同于TodoList
,而Publication
等同于Todo
。
EDIT: Removing an item from the TodoList would look like this: 编辑:从TodoList中删除项目将如下所示:
todolist1.todos.remove(todo1)
.remove()
won't delete a todo entirely, so todo1
would still appear in the other todolists. .remove()
不会完全删除待办事项,因此todo1
仍然会出现在其他的待办事项中。 To totally remove a todo from all todolists, you'd do something like. 为了完全从所有的todolists中删除todo,你会做类似的事情。
todo1.delete()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.