如何考虑外键为空的对象?

时间:2019-06-20 19:51:04

标签: python django

图片我有两个模型:

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


class Card(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    categories = models.ManyToManyField(Category)

现在我想获得以下类别的卡片数量:

cards_by_categories = Card.objects.filter(
    user_id=request.user.id).values('categories__name').annotate(
    num_per_cat=Count('categories__name')
)

我得到了(请考虑针对这个特定用户,我有很多Cards没有类别):

[
  {
    "categories__name": null,
    "num_per_cat": 0          <-- this is incorrect, why 0? I want actual number
  },
  {
    "categories__name": "alol",
    "num_per_cat": 2          <-- this is correct
  },
  {
    "categories__name": "category_name1",
    "num_per_cat": 3          <-- this is correct
  }
]

但是,我希望类别为空的卡片数量不为null,而是不包含类别的实际卡片数量。

我知道,我可以像Card.objects.filter(user_id=request.user.id, categories=None)一样进行查询,但是如何将其合并到一个查询中呢?

0 个答案:

没有答案