Django:无法包含ManyToManyField字段,因为手动指定了“通过"模型 [英] Django: can't include the ManyToManyField field because manually specifies a 'through' model
本文介绍了Django:无法包含ManyToManyField字段,因为手动指定了“通过"模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我搜索了很多遍,仅找到一种解决方案,以通过第3个模型为具有关系的两个模型添加自定义中间模型.而且我按照建议的方式照常申请,但仍然遇到此问题:
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:
不能包含ManyToManyField字段"terms",因为"terms"手动指定了"through"模型
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']})
]
推荐答案
You have to change the admin to include InlineModelAdmin
objects
所以,改变
class AdminPost(admin.ModelAdmin):
fieldsets = [
(None, {'fields':['title', 'content', 'terms']})
]
到
class TermInlineAdmin(admin.TabularInline):
model = Post.terms.through
class AdminPost(admin.ModelAdmin):
fieldsets = [
(None, {'fields':['title', 'content']})
]
inlines = (TermInlineAdmin,)
这篇关于Django:无法包含ManyToManyField字段,因为手动指定了“通过"模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文