【问题标题】:How do you add the mysql query select distinct in python code?如何在 python 代码中添加 mysql 查询 select distinct?
【发布时间】:2012-10-30 01:51:21
【问题描述】:

我正在尝试从我的列/字段category 中显示不同或唯一的值

来自views.py的函数:

def category(request, book_category):
    latest_book_list = Books.objects.all().order_by('id')
    return render_to_response('books/category.html', {'latest_book_list': latest_book_list})

我想要这条线:latest_book_list = Books.objects.all().order_by('id')

执行 mysql 查询: mysql> select distinct category from books;

我尝试过使用Books.objects.filter(category=book_category),但它返回空白。

有什么建议吗?

【问题讨论】:

标签: python mysql django


【解决方案1】:

试试这个...

cateogries = Books.objects.values_list('category', flat=True).distinct()
latest_book_list = Books.objects.filter(category__id__in = categories)

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    相关资源
    最近更新 更多