我有Store
模型,它们为相似的商店相互连接。如您所见,我正在尝试访问score
中的Similarity
字段,该字段被用作Store
模型中ManyToManyField的直通模型。
如何直接从Store对象访问score
字段?
tester.py
store = Store.objects.get(id=1)
print(store) # Store object
print(store.similar_stores.all()[0]) # Store object
print(store.similar_stores.all()[0].similarity.score) # throw the below error
AttributeError:“存储”对象没有属性“相似性”
models.py
class Store(TimeStampedModel):
...
similar_stores = models.ManyToManyField(
'self', through='Similarity', symmetrical=False, related_name='similar_store_of_store')
class Similarity(TimeStampedModel):
similar_target = models.ForeignKey(Store, related_name='similar_target', on_delete=models.CASCADE)
similar_store = models.ForeignKey(Store, related_name='similar_store', on_delete=models.CASCADE)
score = models.FloatField(default=0.0)