0

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.

Letouane
  • 63
  • 1
  • 12

1 Answers1

0

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
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • Many thanks, I turned around the solution and now you wrote that it seems really clear. The reason I didn't find was that I was trying to extract the data from community and not from the product object itself. For anyone that can help, as the current product is not defined in the class, I used the answer directly in my template : `{{ product.community.island.island_name }}` Just perfect, again many thanks ! – Letouane Dec 07 '16 at 08:18
  • As I understand, the only reason why I get the community_name was because of my __str__ function on the Community class. I'll correct the way I extracted it with the dotnotation which is right way ! – Letouane Dec 07 '16 at 08:32