Django通过嵌套外键过滤

时间:2019-07-27 14:37:36

标签: python django django-models django-filter

Souupose我有两个类似的模型:

class Node:
    def __init__(self, word=None, tag=None, grammemes=None):
        self.word = word;
        self.tag = tag;
        self.grammemes = grammemes;
        self.l = None;
        self.r = None;
        self.p = None;
class Tree:
    def __init__(self, grammar):
        self.grammar = grammar;
        self.root = None;
        self.nodes = list();
...

I want to have function like this:

tree.draw()


...and there is pop-up window with my tree.

现在我具有这样的ProductType层次结构:

class ProductType(models.Model):
    name = models.CharField(max_length=50)
    parent = models.ForeignKey('self', related_name='children', bland=True, null=True)


class Product(models.Model):
    name = models.CharField(max_length=50)
    product_type = models.ForeignKey(ProductType)

可以肯定的是,MobilePhone属于电子产品,Apple属于MobilePhone ProductType,最后[galaxy,s10,s8]是Samsung ProductType的产品。 现在如何过滤产品模型以获取所有产品,其中 ProductType = MobilePhone

3 个答案:

答案 0 :(得分:0)

如果您使用的是Django 2,则应添加on_delete(models.CASCADE,models.PROTECTED,models.SET_NULL) 我通常要做的就是尽可能地避免出现错误: prod_type = ProductType.objects.filter(name ___ iexact =“ MobilePhone”)[0] prods = Product.objects.filter(product_type = prod_type)

答案 1 :(得分:0)

也许您需要编写原始查询来获取链的最后一个限制。 如果是无限链,则需要使用循环检查下一个结果。我只是希望您能从更好的开发人员那里得到更好的答案,并且我也能够学习。

答案 2 :(得分:0)

您可以在产品模型中添加一个property,以返回它所属的所有ProductType对象的列表。像这样:

class Product(model.Model):
    name = ...
    product_type = ...

    @property
    def product_types_list(self):
        product_types = []
        obj = self  # reference object
        while obj.product_type is not None:
            product_types.append(obj.product_type)
            obj = obj.product_type
        # Reverse the list to get the proper hierarchy
        product_types.reverse()
        return product_types

之后,您可以像这样过滤产品:

mobile_phone_type = ProductType.objects.get(name='MobilePhone')

mobile_phones = []  # list of filtered mobile phones

for product in Product.objects.all():
    if mobile_phone_type in product.product_types_list:
        mobile_phones.append(product)

您所需的项目将存储在mobile_phones列表中。