繁体   English   中英

AttributeError: '...' object 没有属性 '_set'

[英]AttributeError: '…' object has no attribute '_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'

我在这里做错了什么?

related_name=…参数 [Django-doc]指定了反向关系的名称,因此从FixturePrediction _set , but since you set it to 'fixture' , that of course does not work.如果您不设置它,它默认为 _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,
        related_name='predictions',
        null=True,
        blank=True
    )

然后你可以查询:

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

但最好用以下方式查询:

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

由于您使用了related_name="fixture" ,因此您需要使用它而不是 prediction_set。

下面的代码可以解决问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM