全部,django reverse foreignkey is empty
我想不通這是行不通的。
models.py:
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=64,blank=False,null=False)
parent_model = models.ForeignKey('self',null=True,blank=True,related_name="child_models")
def __unicode__(self):
return u'%s' % (self.name)
def add_child(self,child):
child.parent_model = self
蟒蛇manage.py殼:
>>> foo = MyModel(name='foo')
>>> bar = MyModel(name='bar')
>>> foo.add_child(bar)
>>> bar.parent_model
<MyModel: foo>
>>> foo.child_models.all()
[]
爲什麼是反向外鍵 「child_models」 空當外鍵 「parent_model」 已定?
感謝
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from questionnaire.models import *
>>> foo = TestModel(name='foo')
>>> bar = TestModel(name='bar')
>>> foo.save()
>>> bar.save()
>>> foo.add_child(bar)
>>> bar.get_parent()
<TestModel: foo>
>>> foo.get_children()
[]
def myView(request):
foo = MyModel(name='foo')
bar = MyModel(name='bar')
foo.add_child(bar)
# I don't want to have to save foo or bar before I know that the data is correct,
# or that the user has even pressed submit
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
# somewhere in here is where I want to do the saving to the db
instance = form.save(commit=False)
instance.save()
form.save_m2m()
else:
form = MyForm(instance=foo)
return render_to_response('my_template.html', {"form":form}, context_instance=RequestContext(request))
您是否在設置父級模型後保存孩子? – Wogan
@Wogan - 是的,我已經嘗試在這些操作之前和之後保存foo和bar。它沒有任何區別。 – trubliphone
然後請在創建模型的地方張貼會話,保存它們,然後添加孩子並再次保存,然後訪問反向關係。 –