Skip to main content
 首页 » 编程设计

python之具有模型继承的 Django 多对多

2024年11月01日38bhlsheji

我希望在 ManyToMany 样式关系中使用 Django 的 Generic 模型,其中一个模型继承自基类,而另一个模型不继承可以有对许多继承模型的多个引用,这些继承模型也可以属于该类的许多不同实例(例如,在本例中为 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 admin 而言,我只能添加一个出版物。是否有一种与 ManyToManyField 类似的方法,我可以在其中执行此操作

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

请您参考如下方法:

您必须自己创建多对多关联。

类似的东西:

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()))