[英]Filter ForeignKey choices in an Admin Form based on selections in same models ManytoMany Field?
我正在制作一個“匹配”模型,其中當前包含這些字段:
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")
在我的場景中,“獲勝者”只能是“match_participants”中選擇的外鍵之一,我真的很想將獲勝者字段過濾為僅那些選擇的外鍵。 這可能嗎? 我知道您可以根據進入其他模型的條目過濾外鍵選擇,但對同一個表條目不太確定。
這是我的數據庫結構當前的 UML 示例:
您可以在多對多關系中添加一個額外的字段
https://docs.djangoproject.com/en/2.2/topics/db/models/#extra-fields-on-many-to-many-relationships
模型.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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.