简体   繁体   中英

Two foreign key in the same model from two different model

I need to put two Foreign Keys in a model class from two different models. I would like to relate the third model class to the first and the second.

I've tried something like this:

class A (models.Model)
    id_A = models.IntergerField (primary_key=True)
    #...

    class B (models.Model)
     id_B = models.IntergerField (primary_key=True)
    #...

    class C (models.Model)
      id_A = models.ForeignKey(A)
      id_B = models.ForeignKey(B)

Reading the docs I understand that is not possible to have MultipleColumnPrimaryKeys ... but I Didn't receive any error from django with this models.py

Is it possible? Is there a smarter way?

Thank you!

您做得很好,如果将id_A和id_B关联到同一模型,django会给您一个错误,在这种情况下,只需将related_name属性放在第二个字段中即可。

You can use a many-to-many relationship that automatically creates that intermediate model for you:

from django.db import models


class Publication(models.Model):
    title = models.CharField(max_length=30)


class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication, related_name='articles')

With this you can do both:

publication.articles.all()  # Gives you the articles of the current publication instance
article.publications.all()  # Gives you the publications of the current article instance

Check out docs for many to many

If you need to use any additional fields in that intermediate model, you can tell django which is the through model like this:

from django.db import models


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


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


class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

Check out docs for extra fields on many to many

Also, if you are going for a standard integer auto-increment primary key, django already generates one for you so you don't need to define id_A and id_B .

Django didn't pop up error because you were doing it right. It's totally reasonable that there are multiple foreign keys in one model, just like class C.

In class C, as long as id_A and id_B is the single column primary keys of their own model, it will perfectly work out.

"MultipleColumnPrimaryKeys" you mentioned is a different thing. It means that for a specific table in database, there are multiple columns together to be the table's primary key, which is not supported in Django.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM