【问题标题】:Django filter objects by some referencing conditionDjango通过一些引用条件过滤对象
【发布时间】:2013-02-27 04:18:13
【问题描述】:

在 Django 中,我有两个模型,类别和产品,产品以这种方式引用类别。

class Category(models.Model):
    name = models.CharField(max_length=255)

class Product(models.Model):
    category = models.ForeignKey(Category, null=True)

我想获取至少被一种产品引用的所有类别。

我已经通过这个解决方案实现了我的目标:

class Category(models.Model):
        name = models.CharField(max_length=255)

        def has_product(self):
             products = self.product_set.all()
             if(len(products) > 0):
                   return True
             else:
                   return False

category_list = []

for cat in Category.objects.all(): 
        if cat.has_products():
             category_list.append(cat)

有没有更智能的解决方案?

【问题讨论】:

    标签: django reference filtering


    【解决方案1】:

    您可以通过列表理解来做到这一点:

    cats_with_prod = [c for c in Category.objects.all() if c.product_set.exists()]
    

    但您可以在一个查询中完全在 DB 中完成:

    cats_with_prod = Category.objects.filter(product_set__isnull=False).distinct()
    

    【讨论】:

      【解决方案2】:

      看起来你可以用一个列表理解来做到这一点:

      cats_with_prod = [c for c in Category.objects.all() if c.product_set.exists()]
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2018-01-15
      • 1970-01-01
      • 2017-01-07
      相关资源
      最近更新 更多