Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: can't include the ManyToManyField field because manually specifies a 'through' model

Tags:

python

django

I googled many times and found only one solution to add custom intermediate model for two model having relation through 3rd model. And I applied as usual as suggested but still getting this issue:

can't include the ManyToManyField field 'terms' because 'terms' manually specifies a 'through' model

models.py

class Term(models.Model):
    class Meta:
        db_table = "tbl_term"

    name = models.CharField(max_length=32)

class Post(models.Model):
    class Meta:
        db_table = "tbl_post"

    title = models.CharField(max_length=96)
    content = models.TextField()

    terms = models.ManyToManyField("Term", through="TermRelation")

class TermRelation(models.Model):
    class Meta:
        db_table = "tbl_term_relation"

    term = models.ForeignKey("Term", db_column="id_term")
    post = models.ForeignKey("Post", db_column="id_post")

admin.py

@admin.register(Term)
class AdminTerm(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['name']})
    ]

@admin.register(Post)
class AdminPost(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields':['title', 'content', 'terms']})
    ]
like image 501
Vin.AI Avatar asked Nov 25 '13 19:11

Vin.AI


1 Answers

You have to change the admin to include InlineModelAdmin objects

So, change

class AdminPost(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields':['title', 'content', 'terms']})
    ]

to

class TermInlineAdmin(admin.TabularInline):
    model = Post.terms.through


class AdminPost(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields':['title', 'content']})
    ]

    inlines = (TermInlineAdmin,)
like image 170
karthikr Avatar answered Nov 04 '22 11:11

karthikr