定义默认子级(反向ForeignKey)

发布于 2024-12-01 12:46:06 字数 461 浏览 1 评论 0原文

我有 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 技术交流群。

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

发布评论

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

评论(1

情话难免假 2024-12-08 12:46:06

如果一个Foo可以有多个Bar,那么一个Bar可以属于多个Foo吗?如果是这样,那么您可以使用 ManyToManyFieldthrough 参数轻松解决此问题,如下所示:

class Foo(models.Model):
    name = models.CharField(max_length=128)
    bars = models.ManyToManyField(Bar, through='FooBar')

class Bar(models.Model):
    name = models.CharField(max_length=128)

class FooBar(models.Model):
    foo = models.ForeignKey(Foo)
    bar = models.ForeignKey(Bar)
    is_default = models.BooleanField()

查看 Django 文档 "多对多关系上的额外字段"

作为注释,发布您实际问题的简单版本(即说 PersonGroupFooBar)会有所帮助,因为我们可以更好地了解您实际尝试建模的内容!这样就可以更容易地了解关系实际上应该走向何方。

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 the through parameter, like this:

class Foo(models.Model):
    name = models.CharField(max_length=128)
    bars = models.ManyToManyField(Bar, through='FooBar')

class Bar(models.Model):
    name = models.CharField(max_length=128)

class FooBar(models.Model):
    foo = models.ForeignKey(Foo)
    bar = models.ForeignKey(Bar)
    is_default = models.BooleanField()

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 and Group vs. Foo and Bar) 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.

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