问题描述
我的管理员工作正常,除了一个大的路灯。我在帖子和标签之间创建了多个关系。我可以在管理员中使用CRUD标签,但由于某些原因,我收到以下错误消息: / admin / website / post / add /
< class'website.models.Tag'>没有ForeignKey到< class'website.models.Post'
这是我的模型: p>
class Post(models.Model):
user = models.ForeignKey(User,unique = True)
title = models.CharField(max_length = 80)
slug = models.SlugField()
description = models.TextField(max_length = 1000,blank = True)
created = models .DateField(auto_now_add = True)
#以下信息用于处理目的
management_phone = models.CharField(max_length = 200,blank = True)
management_email = models.CharField(max_length = blank = True)
processing = models.BooleanField(default = False)
transacted = models.BooleanField(default = False)
manual_closed = models.BooleanField(default = False)
def __unicode __(self):
return self.title
class标签(models.Model):
title = models.CharField(max_length = 100)
posts = models.ManyToManyField(Post,blank = True,null = True)
def __uni代码__(self):
返回self.title
再次,问题只出现在我尝试添加一个实例
我的数据库中有一个数据库表website_tag_posts,用于关系。这里有什么问题?
谢谢
您设置发布
ModelAdmin
与标签内联
。
ManyToMany不是外键,所以你不能这样设置一个内联。
如果您需要一个内联,指定您的m2m字段的直通模型作为模型。 m2m字段的通过表包含 Post
表中的 ForeignKey
。
表格标签< - table tag_post - > table post
class TagInline(admin.StackedInline):
model = Tag.posts通过
My admin is working fine other than one big roadbump. I've created a manytomany relationship between posts and tags. I can CRUD tags in my admin but for some reason, I get the following error message:
Exception at /admin/website/post/add/
<class 'website.models.Tag'> has no ForeignKey to <class 'website.models.Post'
Here are my models:
class Post(models.Model):
user=models.ForeignKey(User, unique=True)
title=models.CharField(max_length=80)
slug=models.SlugField()
description=models.TextField(max_length=1000, blank=True)
created=models.DateField(auto_now_add=True)
#following info is for processing purposes
management_phone=models.CharField(max_length=200, blank=True)
management_email=models.CharField(max_length=200, blank=True)
processing=models.BooleanField(default=False)
transacted=models.BooleanField(default=False)
manually_closed=models.BooleanField(default=False)
def __unicode__(self):
return self.title
class Tag(models.Model):
title=models.CharField(max_length=100)
posts=models.ManyToManyField(Post, blank=True,null=True)
def __unicode__(self):
Return self.title
Again, the problem only emerges when I try to Add a Post instance
I have a database table "website_tag_posts" in my database for the relationship. What's the problem here?
Thanks
Sounds to me like you set up your Post
ModelAdmin
with a Tag Inline
.
ManyToMany is not a foreign key, so you can't set up an Inline like that.
If you want an inline, specify the through model for your m2m field as the model instead. The through table for the m2m field contains the ForeignKey
to your Post
table.
table tag <- table tag_post -> table post
class TagInline(admin.StackedInline):
model = Tag.posts.through
这篇关于Django no ForeignKey ...但它是一个ManyToManyField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!