I wrote the following code:
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)
I'm trying to get all the predictions attached to one fixture, using the following code:
f = Fixture.objects.get(sofascore_id="8645471").prediction_set
But this produces the following error:
AttributeError: 'Fixture' object has no attribute 'prediction_set'
What am I doing wrong here?
The related_name=…
parameter [Django-doc] specifies the name of the relation in reverse , so from the Fixture
to the Prediction
s. 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.
You can for example define it as:
class Prediction(models.Model):
market = models.ForeignKey(Market, on_delete=models.CASCADE, blank=True)
fixture = models.ForeignKey(
to=Fixture,
on_delete=models.CASCADE,
,
null=True,
blank=True
)
and then you can query with:
f = Fixture.objects.get(sofascore_id='8645471')
But it might be better to query with:
f = Prediction.objects.filter()
Since you have used related_name="fixture"
you need to use it instead of prediction_set.
The following code will do the trick.
f = Fixture.objects.get(sofascore_id="8645471").fixture
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.