python - 属性错误: '…' object has no attribute '_set'

标签 python django django-models

我编写了以下代码:

class Market(models.Model):
    name = models.CharField(max_length=200)

class Fixture(models.Model):       
    home = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home")
    away = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away")

    league = models.ForeignKey(League, on_delete=models.CASCADE, blank=True)
    round = models.CharField(max_length=200, default=None, blank=True, null=True)

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

    def __str__(self):
        return u'{0} - {1}'.format(self.home.name, self.away.name)

class Prediction(models.Model):
    market = models.ForeignKey(Market, on_delete=models.CASCADE, blank=True)
    fixture = models.ForeignKey(to=Fixture, on_delete=models.CASCADE, related_name="fixture", null=True, blank=True)

我正在尝试使用以下代码将所有预测附加到一个装置:

f = Fixture.objects.get(sofascore_id="8645471").prediction_set

但这会产生以下错误:

AttributeError: 'Fixture' object has no attribute 'prediction_set'

我在这里做错了什么?

最佳答案

related_name=… parameter [Django-doc]指定反向关系的名称,因此来自 FixturePrediction s。如果不设置,则默认为 <i>sourcemodel</i>_set ,但由于您将其设置为 'fixture' ,这当然行不通。

例如,您可以将其定义为:

class Prediction(models.Model):
    market = models.ForeignKey(Market, on_delete=models.CASCADE, blank=True)
    fixture = models.ForeignKey(
        to=Fixture,
        on_delete=models.CASCADE,
        <b>related_name='predictions'</b>,
        null=True,
        blank=True
    )

然后你可以查询:

f = Fixture.objects.get(sofascore_id='8645471')<b>.predictions.all()</b>

但查询可能会更好:

f = Prediction.objects.filter(<b>fixture__sofascore_id='8645471'</b>)

关于python - 属性错误: '…' object has no attribute '_set' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61977965/

相关文章:

python - 我在 Python 中有 2 个代码用于查找素数。为什么在这两个代码中,一个产生结果的速度比另一个快得多

python - 从命令行触发 Django Signal

具有多个抽象基类的 Django 字段类

python split问题我需要数据输出看起来不同

python - Python 中生成器为空时最优雅的分支方法

django - Django搜索多对多查询

python - 呈现 : 'BoundField' object is not iterable 时捕获类型错误

python - 使用 Django 过滤三个表

Django 1.4 TimeField 迁移在 PostgreSQL 上失败

python - 带有钱包推荐和钱包日志的模型架构流程