【问题标题】:Retrieve property of an object through multiple foreignkeys通过多个外键检索对象的属性
【发布时间】:2017-04-22 00:41:06
【问题描述】:

我正在学习 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 对象。

【问题讨论】:

    标签: django python-3.x django-models django-1.10


    【解决方案1】:

    您可以使用点符号来做到这一点。假设你有product 对象,那么你可以这样做

    island_name = product.commuinty.island.island_name
    archipel_name = product.commuinty.island.archipel.archipel_name
    

    【讨论】:

    • 非常感谢,我转了解决方案,现在您写道,它似乎真的很清楚。我没有找到的原因是我试图从社区而不是从产品对象本身中提取数据。对于任何可以提供帮助的人,因为当前产品没有在课堂上定义,我直接在我的模板中使用了答案:{{ product.community.island.island_name }} 完美,再次感谢!
    • 据我了解,我获得 community_name 的唯一原因是因为我在 Community 类上的 str 函数。我会用正确的方式纠正我提取它的方式!
    猜你喜欢
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2021-05-26
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多