我有一个属于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'
答案 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()