簡體   English   中英

如何將mysql查詢轉換為Django模型的ORM?

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

這是我的mysql查詢。

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

如何將此代碼轉換為ORM?

我嘗試這個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

我終於自己得到了答案。 感謝大家!

>>> 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運行此命令!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM