我在查询集结果中发生了一些非常奇怪的事情,我试图在Django项目中启动的线程中访问它。
出现的问题是在线程的 init 中一切正常,但是当我在run()方法中完成应该是相同的操作时 - 它们返回空。代码和结果如下。
有关如何解决这种奇怪行为的任何想法都将不胜感激。
CODE:
class FinalDataCreator(threading.Thread):
def __init__(self, final_form_entry, **kwargs):
print "WORKS", final_form_entry.user_form_entries.all()
self.final_form_entry = final_form_entry
print "WORKS", self.final_form_entry.user_form_entries.all()
self.weirdest_thing = self.final_form_entry.user_form_entries.all()
self.jondykeman = "JonDykeman"
super(FinalDataCreator, self).__init__(**kwargs)
def run(self):
print "EMPTY", self.final_form_entry.user_form_entries.all()
print "EMPTY", self.weirdest_thing
print "WORKS", self.jondykeman
print "WORKS", self.final_form_entry
new_test = FinalDataCreator(final_form_entry)
new_test.start()
结果:
WORKS [<ReviewCustomFormEntry: ReviewCustomFormEntry object>]
WORKS [<ReviewCustomFormEntry: ReviewCustomFormEntry object>]
EMPTY []
EMPTY []
WORKS "JonDykeman"
WORKS ReviewCustomFormEntry
再次感谢JD
答案 0 :(得分:0)
如果您在Python27 \ lib \ threading.py中阅读了线程类的文档,它会说......
If a subclass overrides the constructor, it must make sure to invoke
the base class constructor (Thread.__init__()) before doing anything
else to the thread.
所以改变你的代码,如
class FinalDataCreator(threading.Thread):
def __init__(self, final_form_entry, **kwargs):
super(FinalDataCreator, self).__init__(**kwargs) #why you need to pass **kwargs
print "WORKS", final_form_entry.user_form_entries.all()
self.final_form_entry = final_form_entry
print "WORKS", self.final_form_entry.user_form_entries.all()
self.weirdest_thing = self.final_form_entry.user_form_entries.all()
def run(self):
print "EMPTY", self.final_form_entry.user_form_entries.all()
print "EMPTY", self.weirdest_thing
然后运行您的代码