Django过滤“或”

时间:2013-04-18 20:52:40

标签: django orm mptt

class Tag(models.Model):
  parent = TreeForeignKey('self', null=True, blank=True, related_name='%(class)s_children')
  products = models.ManyToManyField('Product', through="ProductTags", blank=True)

class Product(models.Model):
  tags = models.ManyToManyField('Tag', through="ProductTags", blank=True)

tag_id in POST

currentTag = Tag.objects.get(id=tag_id)

childs = currentTag.get_children().filter(active=True)

应选择具有当前标记的产品或标记为当前标记的子标记

1 个答案:

答案 0 :(得分:1)

from django.db.models import Q
products = Product.objects.filter(Q(tags = tag_id) | Q(tags__parent = tag_id))

应该可以做到这一点。