简体   繁体   中英

How do I convert mysql query to django model's ORM?

This is my mysql query.

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

How do I convert this code to ORM?

I try to this orm. I need to select Max(LogTime) as column. How do I do?

>>> 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

I finally get answer by myself. Thanks everyone!

>>> 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

$ python manage.py inspectdb Run this command!

$ 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM