Generic many-to-many relationships in django admin

后端 未结 2 480
粉色の甜心
粉色の甜心 2021-02-10 12:18

I have few similar models in Django:

class Material(models.Model):
    title = models.CharField(max_length=255)
    class Meta:
        abstract = True

class Ne         


        
2条回答
  •  广开言路
    2021-02-10 12:41

    Shouldn't it work if you just turn Danny's example around and define the generic relation on the side of of the Topic-Model?

    See the example in django's docs: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#using-generic-relations-as-an-inline

    Adapted to this question:

    class Topic(models.Model):
        content_type = models.ForeignKey(ContentType)
        object_id = models.PositiveIntegerField()
        content_object = generic.GenericForeignKey("content_type", "object_id")
    

    It probably makes sense to additionally define the reverse relationsship on each related model.

    class News(models.Model):
        topics = generic.GenericRelation(Topic)
    

    And now you could create a TopicInline and attach Topics to news, articles, whatever ...

    class TopicInline(generic.GenericTabularInline):
        model = Topic
    
    class ArticleAdmin(admin.ModelAdmin):
        inlines = [
            TopicInline,
        ]
    
    class NewsAdmin(admin.ModelAdmin):
        inlines = [
            TopicInline,
        ]
    

提交回复
热议问题