【问题标题】:How do I convert mysql query to django model's ORM?如何将 mysql 查询转换为 django 模型的 ORM?
【发布时间】:2015-10-17 07:53:12
【问题描述】:

这是我的 mysql 查询。

SELECT DeviceUID, Max(LogTime) , count(DeviceUID), Mode
 FROM P2PLog.ConnectResult_Table group by DeviceUID;

如何将此代码转换为 ORM?

我尝试这种形式。我需要选择Max(LogTime) 作为列。我该怎么做?

>>> ct = ConnectresultTable.objects
>>> aaa = ct.values('deviceuid', 'mode').annotate(items=Count('deviceuid'))
>>> print aaa.query
SELECT `ConnectResult_Table`.`DeviceUID`, `ConnectResult_Table`.`Mode`, COUNT(`C
onnectResult_Table`.`DeviceUID`) AS `items` FROM `ConnectResult_Table` GROUP BY
`ConnectResult_Table`.`DeviceUID`, `ConnectResult_Table`.`Mode` ORDER BY NULL

【问题讨论】:

    标签: python mysql django python-2.7 orm


    【解决方案1】:

    $ python manage.py inspectdb运行这个命令!

    $ python manage.py inspectdb > models.py    Save your file using Unix.
    
    class Person(models.Model):
        id = models.IntegerField(primary_key=True)
        first_name = models.CharField(max_length=70)
        class Meta:
           managed = False
           db_table = 'CENSUS_PERSONS'       ( Create unmanaged modes, managed=false)
    
    
    $ python manage.py migrate   ( And install this)
    

    【讨论】:

      【解决方案2】:

      我终于自己得到了答案。谢谢大家!

      >>> ct = ConnectresultTable.objects
      >>> aaa = p2p_ct.values('deviceuid', 'mode').annotate(items=Count('deviceuid'),
      new_status=Max('logtime'))
      >>> print aaa.query
      SELECT `ConnectResult_Table`.`DeviceUID`, `ConnectResult_Table`.`Mode`, COUNT(`C
      onnectResult_Table`.`DeviceUID`) AS `items`, MAX(`ConnectResult_Table`.`LogTime`
      ) AS `new_status` FROM `ConnectResult_Table` GROUP BY `ConnectResult_Table`.`Dev
      iceUID`, `ConnectResult_Table`.`Mode` ORDER BY NULL
      

      【讨论】:

        猜你喜欢
        • 2016-06-04
        • 2019-10-17
        • 1970-01-01
        • 2016-04-20
        • 2020-09-12
        • 2016-12-17
        • 2019-12-10
        • 2011-02-01
        相关资源
        最近更新 更多