0

내가 가지고 다음 모델 :- 외래 키에 따라 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

으로 원하는 목록을 얻을 수 있습니다 당신이 Item''와'ManyToMany'을해야한다고 생각 및'범주'. – 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

대단히 감사합니다! 나는 해결책을 스스로 내놓을 수 있었다. 그러나 바로 코드로 바꿀 것이다. :) Heres my solution. '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 (더보기) if cat_obj == 셀프 및 카테고리 목록 : category_list.reverse() category_list.append (self) return category_list' – JOSEFtw