我正在创建一个"matches“模型,该模型当前包含以下字段:
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示例:

发布于 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
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()然后,对于验证,您可以使用信号连接到参与更新,例如
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)https://stackoverflow.com/questions/64036892
复制相似问题