编辑外键对象

时间:2009-07-12 22:37:23

标签: django

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时,它正在保存/创建对象,但它只是独自站立。我如何重做这段代码,以便在对象已经存在时以及当一个对象不存在时起作用?

1 个答案:

答案 0 :(得分:0)

最后:

foo.bar_field = bar
foo.save()