我想弄清楚如何从我的模型与ForeignKey关系中获取数据。我有以下models.py:Python Django - 访问foreignkey数据
class wine(models.Model):
name = models.CharField(max_length=256)
year = models.CharField(max_length=4)
description = models.TextField()
class collection(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(null=True)
class collection_detail(models.Model):
collection = models.ForeignKey(collection)
wine = models.ForeignKey(wine)
quantity = models.IntegerField()
price_paid = models.DecimalField(max_digits=5, decimal_places=2)
value = models.DecimalField(max_digits=5, decimal_places=2)
bottle_size = models.ForeignKey(bottle_size)
葡萄酒是一个基本的表格,类别详细是引用葡萄酒,并增加了用户特定的数据(如支付的价格),以它的表。 Collection是一组collection_detail对象。
我很在努力如何访问这些模型中的数据。我可以轻松显示特定模型的数据,但在查看特定集合时,我无法访问collection_detail.wine.name数据。我是否需要编写特定的查询来执行此操作?我可以从模板语言访问这些数据吗?我的数据模型在通过管理员查看时显示正确,我可以添加我需要的数据和关系。
感谢您的帮助!
集合包含许多collection_detail。所以没有一个细节可以访问,而是一个列表。要获取此列表的查询集,请使用collection.collection_detail_set –