On Fri, Nov 26, 2010 at 2:34 PM, Seb <sebastien.ram...@gmail.com> wrote:
> Hi all !
>
> I want to use Django on an existing database where every user have his
> own table.
> I want to be able to define one "generic" model for every user and
> choose db_table at runtime
> there is "table_a" and "table_b" which is a sub-table of "table_a"
>
> Database looks like this :
> For user "100" I have:
> table_a_100
> table_b_100
>
> and for user "200" :
> table_a_200
> table_b_200
>
> I've create model like this :
>
> class A(models.Model):
>    class Meta:
>        db_table = 'table_a'
>        managed = False
>    f1 = models.CharField(max_length=12)
>
>
> class B(models.Model):
>    class Meta:
>        db_table = 'table_b'
>        managed = False
>    f1 = models.CharField(max_length=12)
>    a = models.ForeignKey(A)
>
>
> And now the big challenge how can I change db_table at runtime ?
> according to http://code.djangoproject.com/wiki/DynamicModels I have
> created a factory function that change the db_table from "table_a" to
> "table_a_[user]"
> example usage :
> A_100 = factory(A,'100') #change table_a to table_a_100
> it works but I can't use the foreign key
> a=A_100.objects.get(pk=1)
> a.b_set.all() # <== I need B pointed to table_b_100
>
>
> Any idea ?
>
> seb
>

First off, this is a stupid database design. Do you really create new
tables in your DB each time you add a user? Mental.

The factory function you describe does not change the db_table at
runtime, it defines new django models. So when you do this:

> A_100 = factory(A,'100') #change table_a to table_a_100

you are defining a new model class, A_100, which explains why:

> it works but I can't use the foreign key
> a=A_100.objects.get(pk=1)
> a.b_set.all() # <== I need B pointed to table_b_100

Your factory method changes Meta options for the class it defines, it
doesn't change the class members at all, so A_100 will always point at
B, not some class B_100, which hasn't been declared at all. For this
to happen, you must be declaring a B_100 class, which has a foreign
key to A_100, rather than declaring a B class which has a foreign key
to A, and then using A as a basis for creating a new model.

You can make this work though. You can execute code in your models.py
to dynamically generate all your models, as described on the wiki page
you already mentioned.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to