Django no ForeignKey…But it's a ManyToManyFiel

2019-05-10 23:17发布

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

1条回答
劫难
2楼-- · 2019-05-11 00:12

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
查看更多
登录 后发表回答