如何动态创建、同步数据库和访问 django 模型?
我为费用应用程序定义了一个费用模型,
class Expense(models.Model):
pub_date = models.DateTimeField()
amount = models.IntegerField()
memo = models.TextField()
我想创建丢失的单独表来维护不同用户的数据,例如
james_expense_table for james
william_expense_table for william
....
balabala_expense_table for balabala
它们的行为完全相同,就像并行对象一样。唯一的区别是前缀。这样,我可以轻松地通过更多功能扩展应用程序。
那么我怎样才能实现这一目标呢?
我从 django web 阅读了一些抽象模型的内容。但事实上,它们是静态的,硬编码在 *.py 文件中,而不是我想要的。
还有一个问题,对于静态模型(*.py 文件中的硬代码),它可以使用“manage.pysyncdb”命令将模块字段同步到表字段,那么对于动态情况如何做到这一点?
I defined an expense model for an expense application,
class Expense(models.Model):
pub_date = models.DateTimeField()
amount = models.IntegerField()
memo = models.TextField()
and I would like to create lost of separate tables to maintain data for different users, such as
james_expense_table for james
william_expense_table for william
....
balabala_expense_table for balabala
They are exactly same behavior, like parallel objects. The only difference is the prefix. So that, i can easily extend the application with more features.
So how can I achieve this?
I've read some abstract model stuff from django web. But in fact, they are static, hard coded in the *.py files, not what i want.
And one more question, for a static model (hard code in *.py file), it can use "manage.py syncdb" command to sync the module fields to the table fields, so how can do this for the dynamic case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要的可能是使用
ForeignKey
,以便可以将表链接到不同的用户:显然,您需要实现并导入
MyUserField
。访问用户
然后,您可以使用以下方式从
Expense
表或用户的Expense
表:这样您就不需要为每个新用户运行syncdb,而且也不需要静态硬编码在文件中。
What you want is probably to use a
ForeignKey
so that you can link your table to different users:Obviously you need to have a
MyUserField
implemented and imported.You can then access the user from the
Expense
tableOr the
Expense
table from the user using:You then don't require to run syncdb for every new user, and it's not statically hard-coded in the file.