如何动态创建、同步数据库和访问 django 模型?

发布于 2024-10-02 05:21:55 字数 606 浏览 9 评论 0原文

我为费用应用程序定义了一个费用模型,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧情勿念 2024-10-09 05:21:55

您想要的可能是使用 ForeignKey ,以便可以将表链接到不同的用户:

class Expense(models.Model):
    pub_date = models.DateTimeField()
    amount = models.IntegerField()
    memo = models.TextField()
    user = models.ForeignKey(MyUserField)

显然,您需要实现并导入 MyUserField

访问用户

my_expense.user

然后,您可以使用以下方式从 Expense 表或用户的 Expense

my_user.expense_set.all()

:这样您就不需要为每个新用户运行syncdb,而且也不需要静态硬编码在文件中。

What you want is probably to use a ForeignKey so that you can link your table to different users:

class Expense(models.Model):
    pub_date = models.DateTimeField()
    amount = models.IntegerField()
    memo = models.TextField()
    user = models.ForeignKey(MyUserField)

Obviously you need to have a MyUserField implemented and imported.

You can then access the user from the Expense table

my_expense.user

Or the Expense table from the user using:

my_user.expense_set.all()

You then don't require to run syncdb for every new user, and it's not statically hard-coded in the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文