在模型函数内执行原始sql查询?

时间:2017-07-21 16:09:26

标签: python django django-models

我有一个属于Student模型的原始sql查询,所以我想在Student类中创建一个名为get_student的函数,并在那里执行查询而不是我的视图。我该怎么做呢?

有了这样的观点,我会这样做:

view.py:

def index(request):
    query = "..." # complex query
    students_list = Student.objects.raw(query)
    # more code

model.py:

class Student(models.Model):
    name = models.CharField(max_length=255)

我尝试了以下操作:

view.py:

def index(request):
    Student.get_students()

model.py:

class Student(models.Model):
    name = models.CharField(max_length=255)

    def get_students():
        query = "..." # complex query
        students = models.Manager.raw(query)
        return students

错误:必须使用Student实例作为第一个参数调用未绑定方法get_students()(没有取而代之)

view.py:

def index(request):
    Student().get_students()

model.py:

class Student(models.Model):
    name = models.CharField(max_length=255)

    def get_students(self):
        query = "..." # complex query
        students = self.objects.raw(query)
        return students

错误:无法通过学生实例访问管理器

view.py:

def index(request):
    Student.get_students()

model.py:

class Student(models.Model):
    name = models.CharField(max_length=255)

    def get_students(self):
        query = "..." # complex query
        students = models.Manager().raw(query)
        return students

错误:必须使用Student实例作为第一个参数调用未绑定方法get_students()(没有取而代之)

view.py:

def index(request):
    Student().get_students()

model.py:

class Student(models.Model):
    name = models.CharField(max_length=255)

    def get_students(self):
        query = "..." # complex query
        students = models.Manager().raw(query)
        return students

错误:'NoneType'对象没有属性'_meta'

1 个答案:

答案 0 :(得分:2)

这应该是一个经理方法。

class StudentManager(models.Manager):
    def get_students(self):
        query = "..." # complex query
        students = self.raw(query)

class Student(models.Model):
    ...
    objects = StudentManager()

...

students = Student.objects.get_students()