查询集在django shell中不为空但在函数中为空

时间:2019-05-11 04:06:57

标签: django

views.py中有以下功能:

def edit_theorem(theorem):
  print(type(theorem))
  print(theorem.id)
  old_list = theorem.included_elements.all()
  print(old_list)
  ...

这些打印功能的输出为:

<class 'app.models.Theorem'>
65
<QuerySet []>

但是,当我运行python manage.py shellfrom app.models import *t=Theorem.objects.get(id=65)print(t.included_elements.all())时,它会打印一个非空的查询集。

为什么?

我的models.py看起来像这样:

class Element(models.Model):
  included_elements = models.ManyToManyField('Element', through='IncludedElements')
  ...

class IncludedElements(models.Model):
  ...

def Theorem(Element):
  ...

DB是PostgreSQL。

1 个答案:

答案 0 :(得分:0)

在调用函数 edit_theorm 之前不确定自己在做什么,但我认为这是问题所在 尝试

def edit_theorem(theorem_id):
  theorem = Theorem.objects.get(id=theorem_id)
  old_list = theorem.included_elements.all()
  print(old_list)

def edit_theorem(request, id):
  //action within the view

  edit_theorem(id)

  //other action within the view