2

请帮我从我的输出中删除重复项:

视图.py

if request.is_ajax():
        subjects = Subjects.objects.distinct().order_by('-num_of_followers')[:5]
        result = serializers.serialize("json", subjects) 

如您所见distinct(),没有做任何事情。

我现在的输出如下所示:

aaa
aaa
aaa
bbb
ccc

但我希望它是这样的:

aaa
bbb
ccc

更新

现在我的数据库看起来像这样:

Database changed
mysql> SELECT * FROM school_subjects;
+----+----------+---------+------------+---------------------+------------------+
| id | name     | user_id | created_by | created_time        | num_of_followers |
+----+----------+---------+------------+---------------------+------------------+
|  1 | Math 140 |       1 | rrr        | 2012-08-23 12:11:55 |                4 |
|  2 | lll      |       2 | aaa        | 2012-08-23 14:25:13 |                2 |
|  3 | kmkk     |       2 | aaa        | 2012-08-25 14:11:42 |                2 |
|  4 | llll     |       2 | aaa        | 2012-08-25 14:11:57 |                2 |
|  5 | Math 140 |       3 | qqq        | 2012-08-25 15:29:44 |                4 |
|  6 | qweqw    |       3 | qqq        | 2012-08-25 15:30:32 |                1 |
|  7 | lalala   |       3 | qqq        | 2012-08-25 15:38:57 |                1 |
|  8 | kkdkdk   |       3 | qqq        | 2012-08-25 17:49:25 |                1 |
|  9 | aaaa     |       2 | aaa        | 2012-08-27 19:13:49 |                1 |
| 10 | mmcmcm   |       2 | aaa        | 2012-08-27 19:22:10 |                1 |
| 11 | aaaaa    |       2 | aaa        | 2012-08-27 21:17:32 |                1 |
| 12 | Math 140 |       2 | aaa        | 2012-08-27 21:25:07 |                4 |
+----+----------+---------+------------+---------------------+------------------+
12 rows in set (0.00 sec)

我得到的 JSON:

[{"pk": 1, "model": "school.subjects", "fields": {"created_time": "2012-08-23 12:11:55", "num_of_followers": 4, "name": "Math 140", "created_by": "rrr", "user": 1}}, {"pk": 12, "model": "school.subjects", "fields": {"created_time": "2012-08-27 21:25:07", "num_of_followers": 4, "name": "Math 140", "created_by": "aaa", "user": 2}}, {"pk": 5, "model": "school.subjects", "fields": {"created_time": "2012-08-25 15:29:44", "num_of_followers": 4, "name": "Math 140", "created_by": "qqq", "user": 3}}, {"pk": 4, "model": "school.subjects", "fields": {"created_time": "2012-08-25 14:11:57", "num_of_followers": 2, "name": "llll", "created_by": "aaa", "user": 2}}, {"pk": 3, "model": "school.subjects", "fields": {"created_time": "2012-08-25 14:11:42", "num_of_followers": 2, "name": "kmkk", "created_by": "aaa", "user": 2}}]

从这个例子你可以看到我得到了 Math 140 3 次,但我希望它只出现一次。

谢谢你。

4

1 回答 1

2

文档有一些关于使用的具体信息distinct以及它如何受到使用的影响order_by

尝试切换顺序,并指定字段:

Subjects.objects.order_by('created_by', '-num_of_followers')\
    .distinct('created_by')[:5]
于 2012-08-28T23:23:30.977 回答