Django Group By Model Field

时间:2018-05-14 09:20:24

标签: django django-rest-framework

对于此特定模型,我想运行查询并按category分组响应。

class Catalog(models.Model):
    id = models.AutoField(primary_key=True)
    item = models.CharField(max_length=512)
    text = models.TextField()
    category = models.CharField(max_length=512)
    book = models.ForeignKey('Book', on_delete=models.CASCADE)

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

我在stackoverflow上尝试了一些东西,但这并没有帮助我实现我想要的东西,有人可以帮我指出正确的方向。

Catalog.objects.values('category').annotate(category_name=Count('category')).filter(book=123)

串行:

class CatalogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Catalog
        fields = ('id', 'item', 'text', 'category')

查看:

class CatalogViewSet(viewsets.ModelViewSet):

    serializer_class = CatalogSerializer
    permission_classes = [AllowAny]

    def get_queryset(self):
        return Catalog.objects.values('category').annotate(category_name=Count('category')).filter(property=1234)

0 个答案:

没有答案