AttributeError:“ ...”对象没有属性“ _set”

我写了以下代码:

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'

我在这里做错了什么?

评论
  • 情侣~装
    情侣~装 回复

    Since you have used related_name="fixture" you need to use it instead of prediction_set.

    以下代码可以解决问题。

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

  • iid
    iid 回复

    The related_name=… parameter [Django-doc] specifies the name of the relation in reverse, so from the Fixture to the Predictions. If you do not set it, it defaults to the sourcemodel_set, but since you set it to 'fixture', that of course does not work.

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

    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='predictions',
            null=True,
            blank=True
        )

    然后您可以查询:

    f = Fixture.objects.get(sofascore_id='8645471').predictions.all()

    但最好使用以下查询:

    f = Prediction.objects.filter(fixture__sofascore_id='8645471')