我有以下两个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)

在我的模式定义中,我希望从Participants的Angular 访问Participantsoft_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'>.

我该如何解决这个问题?

推荐答案

您可以使用resolver:

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

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

    # ...

Python相关问答推荐

预期LP_c_Short实例而不是_ctyles.PyCStructType

使用decorator 重复超载

socket.gaierror:[Errno -2]名称或服务未知|Firebase x Raspberry Pi

跟踪我已从数组中 Select 的样本的最有效方法

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

Select 用a和i标签包裹的复选框?

Pystata:从Python并行运行stata实例

如何找到满足各组口罩条件的第一行?

OR—Tools中CP—SAT求解器的IntVar设置值

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

组/群集按字符串中的子字符串或子字符串中的字符串轮询数据框

实现自定义QWidgets作为QTimeEdit的弹出窗口

在单个对象中解析多个Python数据帧

如何在Python中获取`Genericums`超级类型?

如何在FastAPI中为我上传的json文件提供索引ID?

CommandeError:模块numba没有属性generated_jit''''

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

如何在TensorFlow中分类多个类

如何使用Numpy. stracards重新编写滚动和?

在pandas数据框中计算相对体积比指标,并添加指标值作为新列