【问题标题】:How to distinct a specified field in Django?如何区分Django中的指定字段?
【发布时间】:2020-12-29 14:14:49
【问题描述】:

我正在使用 djangomysql

假设有一个如下表:


class OrderInfo(models.Model):
    gg_account_id = models.CharField(max_length=45, blank=True, null=True)
    order_status = models.IntegerField(blank=True, null=True)
    gg_status = models.IntegerField(blank=True, null=True)
    uid = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'order_info'

其中保存的数据是:

id  gg_account_id order_status  gg_status   uid 
1   6270491342       2            0          1
2    12321323        2            0          34
3    12321323        2            0          34
4    55551233        1            0          54 
5    55551233        2            0          54
6    55551233        2            0          54
7    55551233        2            0          54

如果有多个具有相同gg_account_id 的数据,我只想获取其中一个。我的预期输出应该是:

1   6270491342          1
2    12321323           34
5    55551233           54

这是我对 orm 查询的试用:

recharge_account_list = OrderInfo.objects.\
                                filter(order_status=2, gg_status=0).\
                                distinct("gg_account_id").\
                                values_list("gg_account_id", "uid", "id")

print(recharge_account_list)

但我总是出错


  File "D:\virtual\Envs\smb_middle_server\lib\site-packages\django\db\backends\base\operations.py", line 171, in distinct
_sql
    raise NotSupportedError('DISTINCT ON fields is not supported by this database backend')
django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database backend

我怎样才能得到预期的结果?

谢谢

【问题讨论】:

    标签: python django


    【解决方案1】:

    解决方案一:使用forloop

    gg_account_ids = set()
    recharge_accounts = []
    for i in recharge_account_list:
        if i[0] not in gg_account_ids:
            gg_account_ids.add(i[0])
            recharge_accounts.append(i)
    recharge_account_list = recharge_accounts
    

    解决方案 2:使用原始 SQL

    recharge_account_list = OrderInfo.objects.raw('SELECT ... FROM Order_info GROUP BY ...')
    

    【讨论】:

    • 你能在这里给我一个有效的 sql,我可以得到我的预期结果吗?谢谢。
    【解决方案2】:

    可以观察到您正在使用mysql 作为数据库。 但是,MySQL 不支持字段上的 distinct。我的意思是 distinct('field_name') 它只支持通用 distinct 所以你只能做 distinct() 操作,但不能在特定字段上。

    distinct documentation Django

    Similar question

    此外,您可以通过使用按特定字段分组来实现。

    Distinct with groupby

    【讨论】:

    • 你能给我一个可以得到我预期结果的建议吗?谢谢
    猜你喜欢
    • 2021-08-31
    • 2011-09-14
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2015-10-21
    • 2016-11-02
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多