前向声明 - django 中没有管理页面?

发布于 2024-07-28 22:26:57 字数 708 浏览 8 评论 0原文

这可能是一个数据库设计问题,但我无法找出更好的方法。 在其他几个模型中,我有这些模型:

class User(models.Model):
  name = models.CharField( max_length=40 )
  # some fields omitted
  bands = models.ManyToManyField( Band )

所以

class Band(models.Model):
  creator = models.ForeignKey( User )
  # some fields omitted
  name = models.CharField( max_length=40 )

基本上,我有一个用户实体,它与乐队实体有多对多的关系。 不同的是,我想要一个特殊的用户,他在网站上“创建”了乐队,以便拥有特殊的编辑功能。 所以我继续添加一个名为 Creator 的外键。 代码无法运行,因为在源代码中 Band 位于 User 之后。 所以我转发声明的class Band(models.Model): pass。 遗憾的是,这似乎不是一个好主意,因为现在 Band 是唯一一个在 django admin 中不显示任何界面元素的模型(Bands 模型在那里,只是无法编辑)。

我的问题是,我应该在模型中进行哪些更改才能使其正常工作? (如果有的话)

This is probably a db design issue, but I couldn't figure out any better. Among several others, I have these models:

class User(models.Model):
  name = models.CharField( max_length=40 )
  # some fields omitted
  bands = models.ManyToManyField( Band )

and

class Band(models.Model):
  creator = models.ForeignKey( User )
  # some fields omitted
  name = models.CharField( max_length=40 )

So basically, I've got a user entity, which has many to many relation with a band entity. The twist is that I want a special user, who "created" the band on the site to have special editing capabilities. So I went forward, and added a ForeignKey called creator. The code could not run, because Band came after User in the source. So I forward declared class Band(models.Model): pass. Sadly, this does not seem to be exatly a good idea, because now Band is the only model that doesn't show up any interface elements in the django admin (Bands model is there, it just can't be edited).

My question is that what change should I make in the models to get this work properly? (if any)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栀梦 2024-08-04 22:26:57

请参阅: http://docs.djangoproject.com/en/dev/ ref/models/fields/#foreignkey,其中表示:

如果您需要在尚未建立的模型上创建关系
尚未定义,您可以使用模型的名称,而不是
比模型对象本身:

 class Car(models.Model):
      manufacturer = models.ForeignKey('Manufacturer')
      # ...

 class Manufacturer(models.Model):
      # ...

See: http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey, which says:

If you need to create a relationship on a model that has not
yet been defined, you can use the name of the model, rather
than the model object itself:

 class Car(models.Model):
      manufacturer = models.ForeignKey('Manufacturer')
      # ...

 class Manufacturer(models.Model):
      # ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文