how to descript the many to one relationship in model when there are more than 1 tables

27 views
Skip to first unread message

Holland_zwz

unread,
Aug 6, 2015, 10:06:45 AM8/6/15
to Django users
Sometimes table have more than one foreign key reference to other tables. Then how to descript it in model?

For eg:

Table A:
create table A (
   oid                  varchar(10)          not null,
   pid                  varchar(10)          not null,
   color               varchar(20)          null
)
alter table A add constraint A_PK primary key (oid)

Table B:
create table B(
   oid                  varchar(10)         not null,
   pid                  varchar(10)         not null,
   name              varchar(100)        null
)
alter table B add constraint B_PK primary key (oid)

Table C:
create table  C (
   id                   varchar(10)          null,
   cid                  varchar(10)          null,
   oid                  varchar(10)          null
)

alter table  C add constraint C_FK1 foreign key (oid) references A(oid)
alter table C add constraint C_FK2 foreign key (oid)  references B(oid)


in this case, how to descript it in model?

class ModelA(models.Model):
      oid = models.CharField(max_length=10,primary_key=True)
      ...

class ModelB(models.Model):
      oid = models.CharField(max_length=10,primary_key=True)
      ...

class ModelC(models.Model):
      oid = models.ForeignKey(...) ?



James Schneider

unread,
Aug 6, 2015, 10:14:25 AM8/6/15
to django...@googlegroups.com

You are probably looking for a many-to-many relationship using an intermediary table:

https://docs.djangoproject.com/en/1.8/topics/db/models/#intermediary-manytomany

-James

--
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...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9b1318e7-87b4-49b2-aad2-3a1dff41fa7f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Holland_zwz

unread,
Aug 6, 2015, 1:18:36 PM8/6/15
to Django users
Hi James,
   Thanks for reply. 

   But i am not got the main point. The problem is the table C's oid column data comes from  A or  B.  I think this is not same as many-to-many relationships.

Thanks
-hollandz


在 2015年8月6日星期四 UTC+8下午6:14:25,James Schneider写道:

Javier Guerra Giraldez

unread,
Aug 6, 2015, 1:21:59 PM8/6/15
to django...@googlegroups.com
On Thu, Aug 6, 2015 at 8:18 AM, Holland_zwz <holla...@gmail.com> wrote:
> But i am not got the main point. The problem is the table C's oid column
> data comes from A or B.


I don't think SQL works that way. at least, it's very much against
any normalization guideline.

--
Javier
Reply all
Reply to author
Forward
0 new messages