Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django-您的sql语法有错误_Python_Python 3.x_Django - Fatal编程技术网

Python Django-您的sql语法有错误

Python Django-您的sql语法有错误,python,python-3.x,django,Python,Python 3.x,Django,我正在尝试执行一个简单的MySQL查询,该查询将在MySQL上运行,而它在Django上会给出任何类型的错误 以下是查询: Summary = myTable.objects.raw("select FROM_UNIXTIME(unixtime, '%%Y/%%m/%%d') as ndate,count(id) as query_count from myTable group by ndate order by query_count DESC") 此行将显示以下错误:

我正在尝试执行一个简单的MySQL查询,该查询将在MySQL上运行,而它在Django上会给出任何类型的错误

以下是查询:

Summary = myTable.objects.raw("select FROM_UNIXTIME(unixtime, '%%Y/%%m/%%d') as ndate,count(id) as query_count from myTable group by ndate order by query_count DESC")
此行将显示以下错误:

Raw query must include the primary key
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(unixtime, '%Y/%m/%d') as ndate,count(id) as query_count from myTable' at line 1")
但如果我将查询编辑为以下内容:
selectid FROM_UNIXITIME….
我将得到以下错误:

Raw query must include the primary key
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(unixtime, '%Y/%m/%d') as ndate,count(id) as query_count from myTable' at line 1")
这是我的模型:

class myTable(models.Model):
    user_id = models.IntegerField()
    username = models.CharField(max_length=150)
    query = models.CharField(max_length=100)
    unixtime = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'mytable'

基本上,查询应该只计算该表每天有多少行,并给出以下输出:
{'2020/06/28':30,'2020/06/27':20…}
。有谁能帮助我如何使查询工作,或者至少如何使用Django ORM执行相同的查询,因为使用原始查询是一场噩梦?提前感谢

此部分<代码>从_UNIXITIME中选择id…必须在id后加逗号,因此它应该如下所示:

select id, FROM_UNIXITIME....
而且group by必须具有id,因此它应该如下所示(如果函数正确):


您应该更喜欢使用Django的queryset而不是原始查询。 基本上,如果要计算上表中不同UnixtTime字段的数量,可以使用以下查询集:

myTable.objects.all().values('unixtime').annotate(count=count('unixtime'))


在上面的查询中,您将使用值queryset获得所有unixtime,并可以使用annotate应用聚合,以获得不同的unixtime及其坐标。

谢谢!问题是,它不会提供MySQL上原始查询的输出,这是一个天数列表和每天记录的总数。如果我改成这个,正如Django所希望的那样,我将得到一个很长的“1”列表,日期接近您还可以使用:from Django.db.models import Count导入计数谢谢!这样做的问题是,我将得到一个很长的“1”列表,而不是像{'date':x,'count':20}这样的值,这意味着计算每天有多少条记录,您将获得与上述查询集相同的格式。将queryset输出分配给一个变量,并对其应用循环。例如:
queryset=myTable.objects.all().values('unixtime')。注释(count=count('unixtime'))
用于queryset中的var:print var