[Answered ]-Django ManyToMany relationship not persisting

1πŸ‘

βœ…

It is a bit hard to understand what is attempting to be done because of the generic names, but I will attempt to rewrite your code using a few recommended conventions, and it should hopefully clear up any errors you are having:

def editFoo(request, foo_id):

    try:
        foo_obj = Foo.objects.get(id=foo_id)
    except Foo.DoesNotExist:
        ...  # Handle error here

    ...  # More code here?

    print foo_obj.linked_bar.count()  # Prints current linked_bar count

    linked_bar_id = request.POST.get('linked-bar-id', '')

    try:
        bar_obj = Bar.objects.get(id=linked_bar_id)
    except Bar.DoesNotExist:
        ...  # Handle error here

    if bar_obj:
       foo_obj.linked_bar.add(bar_obj)
       print foo_obj.linked_bar.count()  # Prints current linked_bar count
    return redirect("/foo/" + foo_id)  # Calls showFoo()


def showFoo(request, foo_id):
    foo_obj = Foo.objects.get(id=foo_id)

    ...  # More code here?
    print foo_obj.linked_bar.count()  # Prints current linked_bar count
    return render(request, 'TEMPLATE.html', {'foo': foo_obj})  # Replace 'TEMPLATE.html' with your template name
πŸ‘€Hybrid

1πŸ‘

The solution turned out to be that there was some other code elsewhere in the application which wiped out foo.linked_bar after I’d added to it, which I did not spot initially. So, a trivial matter in the end, but most annoying.

I’ll accept the other answer due to the useful coding convention suggestions.

πŸ‘€knirirr

Leave a comment