【问题标题】:Django Raw SQL query does not return todays recordsDjango Raw SQL 查询不返回今天的记录
【发布时间】:2016-07-31 04:47:34
【问题描述】:

我正在使用 Django 进行预约系统!我想显示今天的约会。这个原始查询必须返回今天的记录,但它没有返回任何记录!

查询如下所示:

todays_appointments = Appointment.objects.raw("""
    SELECT appointment_Appointment.id,
           loginReg_User.user_name,
           appointment_Appointment.task,
           appointment_Appointment.date,
           appointment_Appointment.time,
           appointment_Appointment.status
    FROM appointment_Appointment
    LEFT JOIN loginReg_User
    ON appointment_Appointment.user_id = loginReg_User.id
    WHERE loginReg_User.id={}
      AND appointment_Appointment.date={}
 ORDER BY appointment_Appointment.time".format(user_id, today"""))

另外,today 看起来像这样:

today = datetime.date.today().

我尝试在 shell 中使用 Appointment.objects.filter(date=today) 运行类似的查询,它运行良好!

Models.py

from __future__ import unicode_literals
from ..loginReg.models import User
from django.db import models
import datetime

class AppointmentValidator(models.Manager):
    def task_validator(self, task):
        if len(task) < 1:
            return False
        else:
            return True

def date_validator(self, date_time):
    present = datetime.now().date()
    if date_time < present:
        return False
    else:
        return True
def status(self, status):
    if status == "missed" or status == "done" or status == "pending":
        return True
    else:
        return False


class Queries(models.Manager):
    def todays_appointments(self, user_id):
        today = datetime.date.today()
        todays_appointments = Appointment.objects.raw("SELECT appointment_Appointment.id, loginReg_User.user_name, appointment_Appointment.task, appointment_Appointment.date, appointment_Appointment.time, appointment_Appointment.status FROM appointment_Appointment LEFT JOIN loginReg_User ON appointment_Appointment.user_id = loginReg_User.id WHERE loginReg_User.id={} AND appointment_Appointment.date={} ORDER BY appointment_Appointment.time".format(user_id, today))
    return todays_appointments

def other_appointments(self, user_id):
    today = datetime.date.today()
    other_appointments = `Appointment.objects.raw("SELECT            appointment_Appointment.id, loginReg_User.user_name, appointment_Appointment.task, appointment_Appointment.date, appointment_Appointment.time, appointment_Appointment.status FROM appointment_Appointment LEFT JOIN loginReg_User ON appointment_Appointment.user_id = loginReg_User.id WHERE loginReg_User.id={} AND appointment_Appointment.date>{} ORDER BY appointment_Appointment.time".format(user_id, today))`
    return other_appointments


class Appointment(models.Model):
    task = models.CharField(max_length=150)
    date = models.DateField(null=False, blank=False)
    time = models.TimeField()
    status = models.CharField(max_length=45)
    user = models.ForeignKey(User)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

    appointmentManager = AppointmentValidator()
    queries = Queries()
    objects = models.Manager()

【问题讨论】:

  • 不要使用。 .format() 用于任何 SQL 查询。它容易受到 SQL 注入的攻击。在字符串中使用%s 并将参数作为列表提交。示例:docs.djangoproject.com/en/1.9/topics/db/sql/…
  • 此外:您在其中所做的事情可以使用 ORM 轻松完成。
  • 关于如何使用 ORM 执行此操作的任何建议?我是 django 的新手,这就像我的第一个完整的项目!欣赏!
  • 类似Appointment.objects.filter(date=today(), user=user).order_by('time')
  • 谢谢,它有效!这只是清除了我思维中的障碍!

标签: python django django-models


【解决方案1】:

Date 是一个 DateField,因此您需要将其与日期进行比较,而不是日期的格式化表示(请参阅此答案:https://*.com/a/18505739/5679413)。通过使用格式,您将今天转换为数字和破折号。您的 SQL 查询需要将其转回日期。 Django 大概会为你解决这个问题。

【讨论】:

  • 如果是这样,那么第二个查询 other_appointments 不应该为我工作!如果我错了,请纠正我。
  • 有效吗?我得到operator does not exist: date &gt; integer
  • 不建议的帖子没有帮助!但是&gt; 的另一个查询对我有用。不知道为什么它不适合你。
  • 您使用的是什么 SQL 风格?我在 PostgreSQL 中遇到错误
  • 我现在正在使用 sqlite!一旦一切正常,就会将其转移到 MySQL!