Django serializer update function very long code












0












$begingroup$


I have written an update method for my API.But in the end it ended up taking more than 100 lines of code.Just wanted suggestions and tips on how to shorten the code



My update method:



 def update(self, instance, validated_data):
levels = self.initial_data.get('levels')
categories = self.initial_data['selectedCategories']
instance.name = validated_data.get('name', instance.name)
instance.description = validated_data.get('description', instance.description)
instance.tenant = self.context['request'].user.tenant
levels_it_has = [workflow_level.level for workflow_level in WorkflowLevel.objects.filter(workflow=instance).order_by('level') ]

for level in levels:
# Check if editing existing level
if WorkflowLevel.objects.filter(workflow=instance,level=level['level']).exists():
level_var = WorkflowLevel.objects.get(workflow=instance,level=level['level'])
level_var.level = level['level']
level_var.operation=level['operation']
level_var.save()
#If creating new Level
else:
level_var = WorkflowLevel()
level_var.workflow = instance
level_var.level = level['level']
level_var.operation = level['operation']
level_var.save()

########### Level Permissions ############3#########

for permission in level['workflow_permissions']:
permission_obj = WorkflowPermission.objects.get(short_name=permission['short_name'])
permissions_in_level = [ perm.permission.short_name for perm in
WorkflowLevelPermission.objects.filter(
level=level_var,permission=permission_obj,
level__workflow=instance).select_related('permission') ]


if not level_permissions.exists():
permission = WorkflowLevelPermission()
permission.level = level_var
permission.permission = permission_obj
permission.save()

new_perms=[ perm.permission.short_name for perm in
WorkflowLevelPermission.objects.filter(
level=level_var,
level__workflow=instance).select_related('permission') ]


####################### DELETE PERMISSIONS ####################################

if len(new_perms) > len(level['workflow_permissions']):
short_names = [perm['short_name'] for perm in level['workflow_permissions'] ]
perm_to_delete = [item for item in new_perms if item not in short_names]
workflow_permission_to_delete = WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance,permission__short_name__in=perm_to_delete)
workflow_permission_to_delete.delete()

if len(level['workflow_permissions']) == 0:
WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance).delete()


####################### DELETE LEVELS ####################################


if len(levels_it_has) > len(levels):
level_numbers = [lev['level'] for lev in levels]
level_to_delete = [item for item in levels_it_has if item not in level_numbers]
workflow_level_to_delete = WorkflowLevel.objects.filter(workflow=instance,level__in=level_to_delete)
workflow_level_to_delete.delete()



##########################################################################

for category in categories:
if not WorkflowCategoryLink.objects.filter(workflow=instance,target_type__short_name=category['short_name']):
workflow_category = WorkflowCategory.objects.get(short_name=category['short_name'])
workflow_category_link = WorkflowCategoryLink()
workflow_category_link.workflow=instance
workflow_category_link.target_type=workflow_category
workflow_category_link.save()

new_categories = [cat.target_type.short_name for cat in WorkflowCategoryLink.objects.filter(workflow=instance).select_related('target_type')]

######################## DELETE CATEGORIES ##############################

if len(new_categories)> len(categories):
short_names = [cacat['short_name'] for cat in categories]
category_to_delete = [item for item in new_categories if item not in short_names]
category_link_to_delete = WorkflowCategoryLink.objects.filter(workflow=instance,target_type__short_name__in=category_to_delete)
category_link_to_delete.delete()

instance.save()
return instance


The update method also has to delete from database by comparing the api and db fields .If user creates new object then it has to be added to database









share







New contributor




Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    0












    $begingroup$


    I have written an update method for my API.But in the end it ended up taking more than 100 lines of code.Just wanted suggestions and tips on how to shorten the code



    My update method:



     def update(self, instance, validated_data):
    levels = self.initial_data.get('levels')
    categories = self.initial_data['selectedCategories']
    instance.name = validated_data.get('name', instance.name)
    instance.description = validated_data.get('description', instance.description)
    instance.tenant = self.context['request'].user.tenant
    levels_it_has = [workflow_level.level for workflow_level in WorkflowLevel.objects.filter(workflow=instance).order_by('level') ]

    for level in levels:
    # Check if editing existing level
    if WorkflowLevel.objects.filter(workflow=instance,level=level['level']).exists():
    level_var = WorkflowLevel.objects.get(workflow=instance,level=level['level'])
    level_var.level = level['level']
    level_var.operation=level['operation']
    level_var.save()
    #If creating new Level
    else:
    level_var = WorkflowLevel()
    level_var.workflow = instance
    level_var.level = level['level']
    level_var.operation = level['operation']
    level_var.save()

    ########### Level Permissions ############3#########

    for permission in level['workflow_permissions']:
    permission_obj = WorkflowPermission.objects.get(short_name=permission['short_name'])
    permissions_in_level = [ perm.permission.short_name for perm in
    WorkflowLevelPermission.objects.filter(
    level=level_var,permission=permission_obj,
    level__workflow=instance).select_related('permission') ]


    if not level_permissions.exists():
    permission = WorkflowLevelPermission()
    permission.level = level_var
    permission.permission = permission_obj
    permission.save()

    new_perms=[ perm.permission.short_name for perm in
    WorkflowLevelPermission.objects.filter(
    level=level_var,
    level__workflow=instance).select_related('permission') ]


    ####################### DELETE PERMISSIONS ####################################

    if len(new_perms) > len(level['workflow_permissions']):
    short_names = [perm['short_name'] for perm in level['workflow_permissions'] ]
    perm_to_delete = [item for item in new_perms if item not in short_names]
    workflow_permission_to_delete = WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance,permission__short_name__in=perm_to_delete)
    workflow_permission_to_delete.delete()

    if len(level['workflow_permissions']) == 0:
    WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance).delete()


    ####################### DELETE LEVELS ####################################


    if len(levels_it_has) > len(levels):
    level_numbers = [lev['level'] for lev in levels]
    level_to_delete = [item for item in levels_it_has if item not in level_numbers]
    workflow_level_to_delete = WorkflowLevel.objects.filter(workflow=instance,level__in=level_to_delete)
    workflow_level_to_delete.delete()



    ##########################################################################

    for category in categories:
    if not WorkflowCategoryLink.objects.filter(workflow=instance,target_type__short_name=category['short_name']):
    workflow_category = WorkflowCategory.objects.get(short_name=category['short_name'])
    workflow_category_link = WorkflowCategoryLink()
    workflow_category_link.workflow=instance
    workflow_category_link.target_type=workflow_category
    workflow_category_link.save()

    new_categories = [cat.target_type.short_name for cat in WorkflowCategoryLink.objects.filter(workflow=instance).select_related('target_type')]

    ######################## DELETE CATEGORIES ##############################

    if len(new_categories)> len(categories):
    short_names = [cacat['short_name'] for cat in categories]
    category_to_delete = [item for item in new_categories if item not in short_names]
    category_link_to_delete = WorkflowCategoryLink.objects.filter(workflow=instance,target_type__short_name__in=category_to_delete)
    category_link_to_delete.delete()

    instance.save()
    return instance


    The update method also has to delete from database by comparing the api and db fields .If user creates new object then it has to be added to database









    share







    New contributor




    Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      I have written an update method for my API.But in the end it ended up taking more than 100 lines of code.Just wanted suggestions and tips on how to shorten the code



      My update method:



       def update(self, instance, validated_data):
      levels = self.initial_data.get('levels')
      categories = self.initial_data['selectedCategories']
      instance.name = validated_data.get('name', instance.name)
      instance.description = validated_data.get('description', instance.description)
      instance.tenant = self.context['request'].user.tenant
      levels_it_has = [workflow_level.level for workflow_level in WorkflowLevel.objects.filter(workflow=instance).order_by('level') ]

      for level in levels:
      # Check if editing existing level
      if WorkflowLevel.objects.filter(workflow=instance,level=level['level']).exists():
      level_var = WorkflowLevel.objects.get(workflow=instance,level=level['level'])
      level_var.level = level['level']
      level_var.operation=level['operation']
      level_var.save()
      #If creating new Level
      else:
      level_var = WorkflowLevel()
      level_var.workflow = instance
      level_var.level = level['level']
      level_var.operation = level['operation']
      level_var.save()

      ########### Level Permissions ############3#########

      for permission in level['workflow_permissions']:
      permission_obj = WorkflowPermission.objects.get(short_name=permission['short_name'])
      permissions_in_level = [ perm.permission.short_name for perm in
      WorkflowLevelPermission.objects.filter(
      level=level_var,permission=permission_obj,
      level__workflow=instance).select_related('permission') ]


      if not level_permissions.exists():
      permission = WorkflowLevelPermission()
      permission.level = level_var
      permission.permission = permission_obj
      permission.save()

      new_perms=[ perm.permission.short_name for perm in
      WorkflowLevelPermission.objects.filter(
      level=level_var,
      level__workflow=instance).select_related('permission') ]


      ####################### DELETE PERMISSIONS ####################################

      if len(new_perms) > len(level['workflow_permissions']):
      short_names = [perm['short_name'] for perm in level['workflow_permissions'] ]
      perm_to_delete = [item for item in new_perms if item not in short_names]
      workflow_permission_to_delete = WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance,permission__short_name__in=perm_to_delete)
      workflow_permission_to_delete.delete()

      if len(level['workflow_permissions']) == 0:
      WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance).delete()


      ####################### DELETE LEVELS ####################################


      if len(levels_it_has) > len(levels):
      level_numbers = [lev['level'] for lev in levels]
      level_to_delete = [item for item in levels_it_has if item not in level_numbers]
      workflow_level_to_delete = WorkflowLevel.objects.filter(workflow=instance,level__in=level_to_delete)
      workflow_level_to_delete.delete()



      ##########################################################################

      for category in categories:
      if not WorkflowCategoryLink.objects.filter(workflow=instance,target_type__short_name=category['short_name']):
      workflow_category = WorkflowCategory.objects.get(short_name=category['short_name'])
      workflow_category_link = WorkflowCategoryLink()
      workflow_category_link.workflow=instance
      workflow_category_link.target_type=workflow_category
      workflow_category_link.save()

      new_categories = [cat.target_type.short_name for cat in WorkflowCategoryLink.objects.filter(workflow=instance).select_related('target_type')]

      ######################## DELETE CATEGORIES ##############################

      if len(new_categories)> len(categories):
      short_names = [cacat['short_name'] for cat in categories]
      category_to_delete = [item for item in new_categories if item not in short_names]
      category_link_to_delete = WorkflowCategoryLink.objects.filter(workflow=instance,target_type__short_name__in=category_to_delete)
      category_link_to_delete.delete()

      instance.save()
      return instance


      The update method also has to delete from database by comparing the api and db fields .If user creates new object then it has to be added to database









      share







      New contributor




      Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I have written an update method for my API.But in the end it ended up taking more than 100 lines of code.Just wanted suggestions and tips on how to shorten the code



      My update method:



       def update(self, instance, validated_data):
      levels = self.initial_data.get('levels')
      categories = self.initial_data['selectedCategories']
      instance.name = validated_data.get('name', instance.name)
      instance.description = validated_data.get('description', instance.description)
      instance.tenant = self.context['request'].user.tenant
      levels_it_has = [workflow_level.level for workflow_level in WorkflowLevel.objects.filter(workflow=instance).order_by('level') ]

      for level in levels:
      # Check if editing existing level
      if WorkflowLevel.objects.filter(workflow=instance,level=level['level']).exists():
      level_var = WorkflowLevel.objects.get(workflow=instance,level=level['level'])
      level_var.level = level['level']
      level_var.operation=level['operation']
      level_var.save()
      #If creating new Level
      else:
      level_var = WorkflowLevel()
      level_var.workflow = instance
      level_var.level = level['level']
      level_var.operation = level['operation']
      level_var.save()

      ########### Level Permissions ############3#########

      for permission in level['workflow_permissions']:
      permission_obj = WorkflowPermission.objects.get(short_name=permission['short_name'])
      permissions_in_level = [ perm.permission.short_name for perm in
      WorkflowLevelPermission.objects.filter(
      level=level_var,permission=permission_obj,
      level__workflow=instance).select_related('permission') ]


      if not level_permissions.exists():
      permission = WorkflowLevelPermission()
      permission.level = level_var
      permission.permission = permission_obj
      permission.save()

      new_perms=[ perm.permission.short_name for perm in
      WorkflowLevelPermission.objects.filter(
      level=level_var,
      level__workflow=instance).select_related('permission') ]


      ####################### DELETE PERMISSIONS ####################################

      if len(new_perms) > len(level['workflow_permissions']):
      short_names = [perm['short_name'] for perm in level['workflow_permissions'] ]
      perm_to_delete = [item for item in new_perms if item not in short_names]
      workflow_permission_to_delete = WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance,permission__short_name__in=perm_to_delete)
      workflow_permission_to_delete.delete()

      if len(level['workflow_permissions']) == 0:
      WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance).delete()


      ####################### DELETE LEVELS ####################################


      if len(levels_it_has) > len(levels):
      level_numbers = [lev['level'] for lev in levels]
      level_to_delete = [item for item in levels_it_has if item not in level_numbers]
      workflow_level_to_delete = WorkflowLevel.objects.filter(workflow=instance,level__in=level_to_delete)
      workflow_level_to_delete.delete()



      ##########################################################################

      for category in categories:
      if not WorkflowCategoryLink.objects.filter(workflow=instance,target_type__short_name=category['short_name']):
      workflow_category = WorkflowCategory.objects.get(short_name=category['short_name'])
      workflow_category_link = WorkflowCategoryLink()
      workflow_category_link.workflow=instance
      workflow_category_link.target_type=workflow_category
      workflow_category_link.save()

      new_categories = [cat.target_type.short_name for cat in WorkflowCategoryLink.objects.filter(workflow=instance).select_related('target_type')]

      ######################## DELETE CATEGORIES ##############################

      if len(new_categories)> len(categories):
      short_names = [cacat['short_name'] for cat in categories]
      category_to_delete = [item for item in new_categories if item not in short_names]
      category_link_to_delete = WorkflowCategoryLink.objects.filter(workflow=instance,target_type__short_name__in=category_to_delete)
      category_link_to_delete.delete()

      instance.save()
      return instance


      The update method also has to delete from database by comparing the api and db fields .If user creates new object then it has to be added to database







      python-3.x django





      share







      New contributor




      Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 5 mins ago









      MohitMohit

      1




      1




      New contributor




      Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Mohit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Mohit is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213786%2fdjango-serializer-update-function-very-long-code%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Mohit is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Mohit is a new contributor. Be nice, and check out our Code of Conduct.













          Mohit is a new contributor. Be nice, and check out our Code of Conduct.












          Mohit is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213786%2fdjango-serializer-update-function-very-long-code%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to make a Squid Proxy server?

          Is this a new Fibonacci Identity?

          19世紀