2009-07-12 64 views
0
class Foo(models.Model) 
    field1 = models.IntegerField() 
    field2 = models.IntegerField() 
    bar_field = models.ForeignKey("Bar", null=True, blank=True) 

在視圖中,我給出了Foo pk,並且從中我需要抓取相應的Bar對象,進行編輯,然後再次保存。什麼是最好的方法來做到這一點?編輯外鍵對象

def my_view(request, foo_pk) 
    foo = get_object_or_404(Foo, pk=foo_pk) 

    bar = foo.bar_field 
    if not bar: 
     bar = Bar() 
     #bar = Bar(foo=foo) # this is normally how I would do it 
          # if I were using ManyToMany 

    bar_form = BarForm(instance=bar) #sent off to the view 

    #[...] 

    bar_form.save() #if bar_field was null, this won't get connected to Foo when saved 

問題是,當我創建Bar的空實例時,它沒有以任何方式連接到Foo。當我保存bar_form時,它正在保存/創建對象,但它只是一個人站立。我該如何重寫這段代碼,以便它在對象已經存在的時候以及當它不存在的時候能夠工作?

回答

0

底:

foo.bar_field = bar 
foo.save()