django Insert or Update record

Please use update_or_create method. This method if a data is exist then updated the details else newly inserted. Reference: https://www.kite.com/python/docs/django.db.models.QuerySet.update_or_create https://djangosnippets.org/snippets/1114/

def GroupOfProduct(request):
    group_id = request.POST.get('group')
    groups = ProductRelatedGroup(id=group_id)
    idproduct = request.POST.get('product')
    for products_id in request.POST.getlist("product"):
        products = Product(id=products_id)
    ProductRelatedGroupAndProduct.objects.update_or_create(id=idproduct,defaults={'product':products,'productrelatedgroup':groups})  
    return redirect(relatedgroup)

Tags:

Python

Django