【问题标题】:Django no ForeignKey...But it's a ManyToManyFieldDjango 没有 ForeignKey ......但它是一个 ManyToManyField
【发布时间】:2011-03-17 21:46:58
【问题描述】:

我的管理员工作正常,除了一个大问题。我在帖子和标签之间创建了多对多关系。我可以在我的管理员中 CRUD 标记,但由于某种原因,我收到以下错误消息:

Exception at /admin/website/post/add/

<class 'website.models.Tag'> has no ForeignKey to <class 'website.models.Post'

这是我的模型:

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

同样,问题仅在我尝试添加 Post 实例时出现

我的数据库中有一个用于关系的数据库表“website_tag_posts”。这里有什么问题?

谢谢

【问题讨论】:

  • 你能发布你的admin.py吗?

标签: django django-models django-admin


【解决方案1】:

在我看来,您将Post ModelAdmin 设置为Tag Inline

ManyToMany 不是外键,所以不能这样设置 Inline。

如果您想要内联,请将 m2m 字段的直通模型指定为模型。 m2m 字段的直通表包含 ForeignKey 到您的 Post 表。

table tag &lt;- table tag_post -&gt; table post

class TagInline(admin.StackedInline):
     model = Tag.posts.through

【讨论】:

    猜你喜欢
    • 2017-05-07
    • 2018-06-26
    • 2016-01-10
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多