tags:

views:

35

answers:

1
class Foo(models.Model)
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    bar_field = models.ForeignKey("Bar", null=True, blank=True)

In a view, I am given the Foo pk, and from that I need to grab the corresponding Bar object, edit it, and then save it again. Whats the best way to do this?

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

The problem is that when I create the empty instance of Bar, it isn't in any way getting connected to Foo. When I save the bar_form, it's saving/creating the object, but it's just standing alone. How can I rework this code so that it works when the object already exists, and also when one doesn't exist?

A: 

At the end:

foo.bar_field = bar
foo.save()
jds