我有带有产品和类别的模型。 类别是产品的外键,并且类别也会自我关联到子类别。 为了获得名称包含某些字符串的类别的产品的查询集,我认为应该有一种比下面这样更聪明的方法 (产品__类别__父母__父母__父母……__名称__包含)
有人可以建议更好的方法吗?谢谢
models.py
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True, null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
class Category(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True,
related_name='children', on_delete=models.CASCADE)
name = models.CharField(max_length=100, unique=True)
class MPTTMeta:
order_insertion_by= ['name']
def __str__(self):
return self.name
def trees(self):
ancestors = self.get_ancestors(ascending=False, include_self=True)
return ' | '.join(category.name for category in ancestors)
context_processor.py
def filter_category(request):
query = request.GET.get('fq', None)
if query is not None:
lookups = Q(category__name__icontains=query) | Q(category__parent__name__icontains=query)\
| Q(category__children__name__icontains=query) | Q(category__parent__parent__name__icontains=query)
results = Product.objects.select_related().filter(lookups)
else:
results = Product.objects.all()
context = {
'results': results
}
return context