Django 架构反向相关对象

问题描述 投票:0回答:1

我有以下两个 Django 模型:

class Participant(models.Model):
    name = models.TextField()
    sport = models.TextField()

    bookmaker = models.ForeignKey(Bookmaker, on_delete=models.CASCADE)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("name", "bookmaker", "sport")

    def __str__(self) -> str:
        return f"{self.name} ({self.sport}) | {self.bookmaker.name}"

class BookmakerParticipant(models.Model):
    sharp_participant = models.OneToOneField(Participant, on_delete=models.CASCADE, primary_key=True, related_name="sharp_participant_match")
    soft_participants = models.ManyToManyField(
        Participant, related_name="soft_participant_matches"
    )

    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

在我的架构定义中,我想从“参与者”角度访问参与者位于“soft_participants”中的所有 BookmakerParticipant 对象。因此,我创建了以下架构:

class UnmatchedParticipantSchema(ModelSchema):
    bookmaker: BookmakerSchema
    soft_participant_matches: BookmakerParticipantSchema

    class Meta:
        model = Participant
        fields = [
            "name",
            "sport",
            "bookmaker",
            "soft_participant_matches"
        ]

但是,这会在 Django 中产生以下错误

ninja.errors.ConfigError: DjangoField(s) {'soft_participant_matches'} are not in model <class 'core.models.Participant'>

我该如何解决这个问题?

python django orm django-ninja
1个回答
0
投票

您可以使用解析器

class UnmatchedParticipantSchema(ModelSchema):
    bookmaker: BookmakerSchema
    soft_participant_matches: list[BookmakerParticipantSchema]

    @staticmethod
    def resolve_soft_participant_matches(obj):
        return list(obj.soft_participant_matches.all())

    # ...
© www.soinside.com 2019 - 2024. All rights reserved.