我写了以下代码:
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.以下代码可以解决问题。
The
related_name=…
parameter [Django-doc] specifies the name of the relation in reverse, so from theFixture
to thePrediction
s. If you do not set it, it defaults to thesourcemodel_set
, but since you set it to'fixture'
, that of course does not work.例如,您可以将其定义为:
然后您可以查询:
但最好使用以下查询: