0

我有以下型號:獲取所有的父類的Django - 跟隨外鍵UP

class Category(models.Model): 
    name = models.CharField(max_length=255) 
    parent = models.ForeignKey("self", blank=True, null=True) 

    class Meta: 
     verbose_name = _("category") 
     verbose_name_plural = _("categories") 

    def __unicode__(self): 
     return self.name 


class Item(models.Model): 
    name = models.CharField(max_length=100, verbose_name=_("name")) 
    keywords = models.CharField(max_length=255, verbose_name=_("keywords")) 
    category = models.ForeignKey(Category) 

    class Meta: 
     abstract = True 
     verbose_name = _('item') 
     verbose_name_plural = _('items') 


class Product(Item): 
    price = models.DecimalField(decimal_places=2, max_digits=8, verbose_name=_("price")) 
    brand = models.ForeignKey(Brand, verbose_name=_("brand")) 
    article_number = models.CharField(max_length=255, verbose_name=_("article_number")) 

    def __unicode__(self): 
     return self.name 

    class Meta: 
     verbose_name = _('product') 
     verbose_name_plural = _('products') 

比方說,我在數據庫以下幾類:

ID  NAME  PARENT_ID 
1  Products  null 
2  Phones   1 
3  iPhones   2 

我可以得到頂級類通過執行以下操作:

#This is a product with the category "iPhones" 
product.category.parent.parent 

但這並不好,因爲產品可以是x個類別的深度。

如何獲取數組或其他類中的所有相關類?

Wanted output = [iPhones, Phones, Products] 
+0

得到想要的清單,我認爲你應該有'ManyToMany'用'Item'和「類別」。 – Rohan

回答

2

寫模型屬性方法的項目類:

class Item(models.Model): 
    @property 
    def all_categories(self): 
     categories = [] 
     current_category = self.category 
     while current_category is not None: 
      categories.append(current_category) 
      current_category = current_category.parent 
     return categories 
     #optional return reversed list: 
     #return list(reversed(categories)) 

現在你可以用

product.all_categories 
+1

非常感謝!我設法自己想出一個解決方案,但我會立即切換到您的代碼:) 繼承人我的解決方案。 'DEF get_all_categories(個體,cat_obj): category_list = [] 如果cat_obj.parent_id: C = cat_obj.parent category_list.append(c)中更 = self.get_all_categories(C) category_list.extend (more) if cat_obj == self and category_list: category_list.reverse() category_list.append(self) return category_list' – JOSEFtw