Thursday, March 28, 2013

Re: manytomany field and intermediary table from a legacy database

Hey Vittorio,

ManyToManyField has one optional argument for specifying
db_table(http://bit.ly/10ciWdu).

Since, you have different column names, you should create a new model.
and specify that model as `through` argument(http://bit.ly/10cjdgz).
And set `db_table` in `Meta` class of this model.

In this new `through` model, specify all fields and for each field you
can set `db_column` (http://bit.ly/10cjjEU).

Example code

class Person(models.Model):
name = models.CharField(max_length=128)

def __unicode__(self):
return self.name

class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')

def __unicode__(self):
return self.name

class Membership(models.Model):
person = models.ForeignKey(Person, db_column="person_column_name")
group = models.ForeignKey(Group, db_column="group_column_name")
date_joined = models.DateField(db_column="date_joined_column_name")
invite_reason = models.CharField(max_length=64,
db_column="invite_reason_column_name")

class Meta:
db_table = "membership_table_name"

On Wed, Mar 27, 2013 at 11:28 PM, Vittorio <ml-vic@de-martino.it> wrote:
> I know that when I define a manytomany field automagically "behind the scene
> Django creates an intermediary join table to represent the many-to-many
> relationship".
> Now I have a legacy MySQL db, feeded by an existing procedure built in
> Filemaker via ODBC, which I would like to use with django too. In this
> legacy db the "intermediary join table" already exists but with a different
> name and with different name fields.
> How can I tell Django to use that table without creating a new one?
> An example would be very useful.
> Bye from Rome
> Vittorio
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscribe@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>



--

Sincerely,
Pankaj Singh
http://about.me/psjinx

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

No comments:

Post a Comment