如何在 Django 中创建依赖模型关系

发布于 2024-10-11 08:06:42 字数 501 浏览 1 评论 0原文

我正在尝试为以下场景创建一个 Django 模型:

有几个俱乐部。每个俱乐部都有一名领导者和多名成员。领导者也是会员。

到目前为止,这些是我的模型:

class Club(models.Model):
    name = models.CharField(max_length=50)
    leader = models.ForeignKey('Member', related_name='+')
class Member(models.Model):
    name = models.CharField(max_length=50)
    club = models.ForeignKey(Club)

在管理界面中,如果不先创建俱乐部,我就无法添加成员,但如果不创建指定为领导者的成员,我就无法创建俱乐部。我尝试将 Blank=True 添加到领导者foreignkey关系中,但仍然不起作用。

我应该如何针对这种情况创建模型?

提前致谢!

I am trying to create a Django model for the following scenario:

There are several Clubs. Each Club has a single leader and several members. The leader is also a member.

These are my models so far:

class Club(models.Model):
    name = models.CharField(max_length=50)
    leader = models.ForeignKey('Member', related_name='+')
class Member(models.Model):
    name = models.CharField(max_length=50)
    club = models.ForeignKey(Club)

In the admin interface, I can't add a member without first making a club, but I can't make a club without creating a member to designate as the leader. I tried adding Blank=True to the leader ForeignKey relationship, but it still doesn't work.

How should I create the models for the situation?

Thanks in advance!

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

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

发布评论

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

评论(2

¢好甜 2024-10-18 08:06:42

创建一个 ClubLeader 模型类,其中列作为俱乐部的外键,而会员则作为领导者。强制该表中俱乐部+会员 ID 的唯一性,以确保您没有多个领导者。从您的俱乐部班级中删除“领导者”。

另外,我不会加入任何有像我这样的人作为会员的俱乐部(格劳乔·马克思)

Create a ClubLeader model class, with columns as Foreign Keys to a Club and a Member to be the leader. Enforce uniqueness for Club+Member ids in that table to make sure you dont have multiple leaders. Remove 'leader' from your Club class.

Also, I wouldn't join any club that would have someone like me for a member (Groucho Marx)

梨涡少年 2024-10-18 08:06:42

有关详细信息,Blank=True 并不意味着数据库中的字段可以为空。它仅意味着使用 ModelForm 时表单字段可以为空(或者可能只是管理员 - 任一/或)。您想要的是 blank=True, null=True。这允许在表单/管理面板中使用空值和空白值。

不过,我仍然会同意 Spacedman 的回答。提供一张位于“中间”的单独桌子。这样,您就可以强制要求会员必须属于某个俱乐部。

For further information, Blank=True doesn't mean that the field in the database can be null. It only means that a form field can be blank when using a ModelForm (Or perhaps just the admin - either/or). What you want is a blank=True, null=True. That allows a null value, and a blank value in the form/admin panel.

I would still go with Spacedman's answer though. Provide a separate table that sits 'inbetween'. This way, you enforce that Members must belong to a club.

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