Django多对多与模型继承

2 投票
1 回答
645 浏览
提问于 2025-04-17 22:55

我想在Django中使用Generic模型,建立一种ManyToMany的关系。具体来说,就是一个模型从一个基类继承,而另一个模型不继承,可以有多个对那些继承模型的引用。而那些继承的模型也可以属于这个类的多个不同实例(比如在这个例子中是Author)。我的模型结构大概是这样的:

from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType

class BaseModel(models.Model):
    class Meta:
        abstract = True

class Book(BaseModel):
    pass

class Article(BaseModel):
    pass

除了其他从BaseModel继承的模型外,我还有:

class Author(models.Model):
    object_id = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    publications = generic.GenericForeignKey('content_type', 'object_id')

不过,这似乎不允许我在Author模型中添加多个出版物。在这种情况下,所有的出版来源可以有很多作者,而作者也可以有很多出版物,但在Django的管理界面中,我只能添加一个出版物。有没有类似ManyToManyField的方式,让我可以这样做:

>>> a = Author()
>>> a.publications.add(Book())
>>> a.publications.add(Article())

1 个回答

2

你需要自己创建多对多的关联。

像这样:

class AuthorPublication(models.Model):
    author = models.ForeignKey(Author, related_name='publications')
    object_id = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    class Meta:
        unique_together = (
            ('object_id', 'content_type'),
        )

然后你可以这样使用它:

>>> a = Author()
>>> a.publications.add(AuthorPublication(content_object=Book()))
>>> a.publications.add(AuthorPublication(content_object=Article()))

撰写回答