Search code examples
djangopython-3.xdjango-modelsdjango-1.10

Retrieve property of an object through multiple foreignkeys


I'm learning Django and I have chained different classes Archipel -> Island -> Community in order to localize items to be published in a website (Communities belong to only one Island which belongs ton only one Archpelago). Maybe I did wrong but here is how I coded :

#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

In the following class, I can easily get the community name of the product thanks to the 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')

How can I retreive the island_name and archipelago property of my product ? I tried

island = Community.select_related('island').get()

but it returns me a QuerySet of all islands. So I tried "community" but Django answers that ForeignKey object don't have a slelect_related object.


Solution

  • You can do that using dotnotation. Let say you have product object, then you can do this

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