AttributeError: '…' object has no attribute '_set'

Viewed 637

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?

2 Answers

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.

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

and then you can query with:

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

But it might be better to query with:

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

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
Related