我是python和django的新手,我想在新用户注册时(当然,以python方式)在数据库中动态添加表,换句话说,当用户向模型中插入新数据时为该条目显式创建一个表,以添加与该条目相关的额外数据。
我认为python有一种简单的方法来处理这种情况
谢谢。
答案 0 :(得分:0)
您需要有2个表:Users和Todos。如果您不想编写自定义用户,则User
模型已经存在于Django中,因此您需要添加的是Todos模型
从django.contrib.auth.models导入用户
Class Todo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='todos')
name = models.CharField(max_length=50)
note = models.TextField()
当您拥有ID为john
的{{1}},alen
,bob
用户时,您可以:
1,2,3
让我们根据您的架构为john = User.objects.get(id=1)
alen = User.objects.get(id=2)
bob = User.objects.get(id=3)
创建Todo
:
alen
让我们根据您的架构为Todo.objects.create(user=alen, name='visit', note='Visit Doc.')
Todo.objects.create(user=alen, name='Buy', note='Buy Radio')
创建Todo
:
john
让我们根据您的架构为Todo.objects.create(user=john, name='pay bill', note='some large text')
Todo.objects.create(user=john, name='watch Dog', note='detail')
Todo.objects.create(user=john, name='play game', note='detail')
创建Todo
:
bob
为了获得Todo.objects.create(user=bob, name='call', note='call John')
Todo.objects.create(user=bob, name='Meet', note='meet jane')
的特定用户(例如Todo
),您可以:
bob
或
bob_todos = Todo.objects.filter(user=bob)
根据bob_todos = bob.todos.all()