【问题标题】:Get all parent categories Django - Follow foreign key UP获取所有父类 Django - 跟随外键 UP
【发布时间】:2014-04-25 16:22:43
【问题描述】:

我有以下型号:

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]

【问题讨论】:

  • 我认为你应该拥有ManyToManyItemCategory

标签: django foreign-key-relationship categories django-select-related django-related-manager


【解决方案1】:

为项目类编写一个模型属性方法:

  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

【讨论】:

  • 非常感谢!我自己设法想出了一个解决方案,但我会立即切换到您的代码 :) 这是我的解决方案。 def get_all_categories(self, cat_obj): category_list = [] if cat_obj.parent_id: c = cat_obj.parent category_list.append(c) more = 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
猜你喜欢
  • 2021-01-13
  • 2011-08-02
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2014-01-13
相关资源
最近更新 更多