0

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?

Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
William
  • 239
  • 1
  • 2
  • 11

1 Answers1

0

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.

Antoine Pelisse
  • 12,871
  • 4
  • 34
  • 34
  • thanks. but this solution is not good enough for me. I still want to **many** tables in stead of one so as to make each table **as short as possible**. Isolate data of users is very important to my application. – William Nov 09 '10 at 17:04
  • Table length will probably not be relevant as you should have an index on the user field. Concerning the "data isolation", you may have to be more explicit on what you need, but if you want the user to be able to see only its table, then you can maybe try to create some "views". I don't see any other easy solution to dynamically create the tables. – Antoine Pelisse Nov 10 '10 at 08:03