我正在学习 Django,并且我已经链接了不同的类 Archipel -> Island -> Community,以便本地化要在网站上发布的项目(社区只属于一个岛,而该岛只属于一个 Archpelago)。也许我做错了,但这是我的编码方式:
#models.py
class Archipel(models.Model):
"""docstring for Archipel."""
archipel_name = models.CharField(max_length=200)
def __str__(self):
return self.archipel_name
class Island(models.Model):
"""docstring for Archipel."""
archipel = models.ForeignKey(Archipel, on_delete=models.CASCADE)
island_name = models.CharField(max_length=200)
def __str__(self):
return self.island_name
class Community(models.Model):
"""docstring for Archipel."""
island = models.ForeignKey(Island, on_delete=models.CASCADE)
community_name = models.CharField(max_length=200)
community_zipcode = models.IntegerField(default=98700)
def __str__(self):
return self.community_name
在下面的课程中,我可以通过 ForeignKey 轻松获得产品的社区名称:
class Product(models.Model):
community = models.ForeignKey(Community, on_delete=models.CASCADE)
island = # community->island
archipelago = # community->island->archipelago
Product_title = models.CharField(max_length=200)
Product_text = models.TextField()
Product_price = models.IntegerField(default=0)
Product_visible = models.BooleanField(default=False)
pub_date = models.DateTimeField('date published')
如何检索我的产品的 island_name 和 archipelago 属性?我试过了
island = Community.select_related('island').get()
但它返回给我一个所有岛屿的查询集。所以我尝试了“社区”,但 Django 回答说 ForeignKey 对象没有 slelect_related 对象。