ariadne-django icon indicating copy to clipboard operation
ariadne-django copied to clipboard

Deleting items by id

Open ccsv opened this issue 2 years ago • 3 comments

I find this to be a good way of setting up a delete by id:


type_defs = gql("""
   type Document {
        id:ID
        name: String!
   }

 type DeleteResults{
       success:[String]
       errors:[String]
   }

type Mutation{
DeleteDocument(input:[DocumentUpdate]): DeleteResults
}
"""

@mutation.field("DeleteDocument")
def DeleteDocument(*_, input):
    deleted =[]
    errors =[]
    for inputs in input:
        try:
           id = inputs.get("id")
           doc = Document.objects.get(pk=id)
           deleted.append("id "+ id+": "+ doc.name +" document deleted")
           doc.delete()
        except Document.DoesNotExist:
            errors.append("id: "+id+" not found")
    return {'success': deleted, 'errors': errors}

For the function just replace the model Document with whatever model. The results are the same for any model where a string is returned of the items you deleted and the errors. Is there a way some way to write the code so we can just plug in the django models to a function / class in this setup so less code is written? (I am not good at meta programming but find myself repeating this pattern)

ccsv avatar Jul 26 '22 12:07 ccsv