首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否根据相同型号ForeignKey字段中的选择过滤管理窗体中的ManytoMany选项?

问是否根据相同型号ForeignKey字段中的选择过滤管理窗体中的ManytoMany选项?
EN

Stack Overflow用户
提问于 2020-09-24 06:03:36
回答 1查看 31关注 0票数 0

我正在创建一个"matches“模型,该模型当前包含以下字段:

代码语言:javascript
复制
event = models.ForeignKey(Event, on_delete=models.RESTRICT)
match_participants = models.ManyToManyField(Wrestler, on_delete=models.RESTRICT, null=True, blank=True,)
match_type = models.CharField(max_length=25, choices=match_choices, default=BLOCK)
match_result = models.CharField(max_length=25, choices=result_choices, default=NOT_OC)
winner = models.ForeignKey(Wrestler, on_delete=models.RESTRICT, null=True, blank=True, related_name="winner")

在我的场景中," winner“只能是"match_participants”中选择的外键之一,我真的希望将winner字段过滤到那些选择的外键。这个是可能的吗?我知道你可以根据其他模型中的条目来过滤外键选择,但对相同的表条目就不太确定了。

下面是我的数据库结构的UML示例:

​

​

EN

回答 1

Stack Overflow用户

发布于 2020-09-24 07:52:59

您可以在ManytoMany关系中添加额外的字段

https://docs.djangoproject.com/en/2.2/topics/db/models/#extra-fields-on-many-to-many-relationships

models.py

代码语言:javascript
复制
class Match(models.Model):
    wrestlers = models.ManyToManyField(Wrestler, through='Participation' )
    ...



class Participation(models.Model):
    wrestler = models.ForeignKey(Wrestler, on_delete=models.CASCADE)
    match = models.ForeignKey(Match, on_delete=models.CASCADE)
    winner = models.BooleanField()

然后,对于验证,您可以使用信号连接到参与更新,例如

代码语言:javascript
复制
def match_wrestlers_changed(sender, *args, **kwargs):
    if invalid:
        raise ValidationError('There already a winner.')

m2m_changed.connect(
    match_wrestlers_changed,
    sender=Match.wrestlers.through)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64036892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档