定义默认子级(反向ForeignKey)
我有 2 个模型 Foo 和 Bar。每个 Foo 都有多个 Bar,但其中一个需要是“默认”的。此时,Bar 中有一个指向 Foo 的外键,但现在我需要一种方法来指定属于 Foo 的 Bar 中的哪个是默认值。我尝试在 Foo 中设置另一个指向 Bar (具有唯一的 related_name )的外键,但出现各种错误(包括在 django-admin 模板中)。
到目前为止的代码:
class Foo(models.Model):
default_bar = models.ForeignKey('Bar')
class Bar(models.Model):
foo = models.ForeignKey(Foo)
我对全新的解决方案绝对没有问题,因为无论如何我可能都做错了。我能想到的唯一的其他方法是有一个单独的表来连接 Foos 和 Bars 并使 Foo 部分唯一,但这使得管理界面变得混乱。
I have 2 models Foo and Bar. Each Foo has multiple Bars, but one needs to be the "default". At this point I have a foreignkey in Bar pointing to Foo, but now I need a way to specify which of the Bar's belonging to Foo is the default. I tried setting another foreignkey in Foo that points to a Bar (with a unique related_name), but I get all sorts of errors (including in the django-admin templates).
Code so far:
class Foo(models.Model):
default_bar = models.ForeignKey('Bar')
class Bar(models.Model):
foo = models.ForeignKey(Foo)
I have absolutely NO problem with a completely new solution as I'm probably doing it wrong anyways. The only other way I can think of is to have a separate table that connects Foos and Bars and having the Foo part unique, but that makes the admin interface a MESS.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果一个Foo可以有多个Bar,那么一个Bar可以属于多个Foo吗?如果是这样,那么您可以使用
ManyToManyField
和through
参数轻松解决此问题,如下所示:查看 Django 文档 "多对多关系上的额外字段" 。
作为注释,发布您实际问题的简单版本(即说
Person
和Group
与Foo
和Bar
)会有所帮助,因为我们可以更好地了解您实际尝试建模的内容!这样就可以更容易地了解关系实际上应该走向何方。If a Foo can have multiple Bars, then can a Bar belong to multiple Foos? If so then you can solve this really easily with a
ManyToManyField
and thethrough
parameter, like this:Check the Django documentation on "Extra fields on many-to-many relationships".
And just as a note, posting a simple version of your actual problem (ie. saying
Person
andGroup
vs.Foo
andBar
) helps, as we get a better understanding of what you're actually trying to model! That way it's easier to see where the relationships should actually go.