如何在Django中使用ManyToManyField访问模型的字段

时间:2019-05-31 21:51:59

标签: django

我有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)

0 个答案:

没有答案