[SOLVED] Deleting a ManytoMany Relationship Data in Django Project


This Content is from Stack Overflow. Question asked by A_K

I have a dictionary with several keys and values to them. I have a view where there is a condition if the value of one specific key is exisiting equals the same numebr of a POST request to update only specific other Keys here is query to get a better idea:

<QuerySet [{'id': 87, 'active': False, '........': '.....', '......': '......', 'log_order': 1, 'lo
g_weight': 10.0, 'log_repetitions': 10, 'date': .....)}]

In my views I am trying to check if the log_order is the same as the POST request the is submitted by the user and if is exisitng to change the values of lo
g_weight and log_repetitions.

                if active_session.log.values():
                    for i in active_session.log.values():
                        # print("i[log_order] is equal to:", i['log_order'])
                        existing = i['log_order']
                        new = data.log_order
                        print(existing, new)
                        if int(existing) == int(new):
                            print("Available in Session")

                    print('Log added to Session')

here is the post just to know more context:

            if form.is_valid():
                data = Log()
                data.log_order = request.POST.get('log_order')
                data.log_repetitions = form.cleaned_data['log_repetitions']
                data.log_weight = form.cleaned_data['log_weight']
                data.save()  # save data to table     

I have tried to save the data and update() but nothing is changing the dictionary the same exisiting outcome is printed and the new data is not replacing the existing ones. My objective is replace and avoid duplicating.


I have tried and tested your code and found some issues with it.
Below, there is the code snippet I tested and it works.

I am not completely sure what is the purpose for the code, but I think you might find the method update_or_create useful (also works on related managers such as your log). Here is a link to Django docs.

def addlog(request, id):
    if request.method == 'POST':
        # Moved this part to the POST section of the view. It is sufficient to simplify
        # the query in this way. Also, you probably want to check if there are sessions
        # in the DB. Otherwise, the code would break. This returns a 404 in case there
        # are absolutely no sessions.
        active_session = ActiveSession.objects.last()
        if active_session is None:
            return Http404()

        form = LogForm(request.POST)
        if form.is_valid():
            data = Log()
            # Use form.cleaned_data instead of log_order. Form validates the data, POST dict doesn't.
            data.log_order = form.cleaned_data['log_order']
            # Ignored because it's missing from the model code
            # data.log_repetitions = form.cleaned_data['log_repetitions']
            # data.log_weight = form.cleaned_data['log_weight']

            # Use Django ORM querysets instead of values()
            # See https://www.django-antipatterns.com/antipattern/over-use-of-values.html
            active_session_logs = active_session.log.filter(log_order=data.log_order)
            if active_session_logs.exists():
                # Suggestion: try to use update() instead of a combination of delete & add.
                # It reduces two SQL queries to one.
            # After using RelatedManager.add(), no need to call save(), the changes
            # are persisted in the DB simply by using add().

            # Always redirect after successfully processing the form.
            return redirect(reverse('test_73764999:add-log', args=(data.id,)))
            # If there are errors, re-render the same form with errors
            return render(request, 'test_73764999/form.html', {
                'form': form, 'id': id,
        # If this is a GET request, render an empty form
        form = LogForm()

    return render(request, 'test_73764999/form.html', {
        'form': form, 'id': id,

This Question was asked in StackOverflow by A_K and Answered by vinkomlacic It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?