![](/img/trans.png)
[英]AttributeError: '***' object has no attribute '***_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]指定了反向關系的名稱,因此從Fixture
到Prediction
。 _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.