Best way to do a delete operation with GraphQL + graphene - graphql

I'm struggling to get my Delete operation working.
My Create, Read and Update are working fine, but a Delete has nothing to return.
class DeleteEmployeeInput(graphene.InputObjectType):
"""Arguments to delete an employee."""
id = graphene.ID(required=True, description="Global Id of the employee.")
class DeleteEmployee(graphene.Mutation):
"""Delete an employee."""
employee = graphene.Field(
lambda: Employee, description="Employee deleted by this mutation.")
class Arguments:
input = DeleteEmployeeInput(required=True)
def mutate(self, info, input):
data = utils.input_to_dictionary(input)
#data['edited'] = datetime.utcnow()
employee = db_session.query(
EmployeeModel).filter_by(id=data['id'])
employee.delete(data['id'])
db_session.commit()
#employee = db_session.query(
#EmployeeModel).filter_by(id=data['id']).first()
#return DeleteEmployee(employee=employee)
What is the best way to delete an entry?
I assume I have to return an OK or an Error.
When I run my mutation:
mutation {
deleteEmployee (input: {
id: "RW1wbG95ZWU6MQ=="
})
}
I get the error Field \"deleteEmployee\" of type \"DeleteEmployee\" must have a sub selection."
Note the commented out lines

Try replacing employee = graphene.Field... with ok = graphene.Boolean() and then make the last line of your mutate method return DeleteEmployee(ok=True)
Your mutate method will then look something like:
def mutate(self, info, input):
... skipping deletion code ...
db_session.commit()
return DeleteEmployee(ok=True)

Related

get new value in django admin widget

I am working on creating a widget so clients can easily modify model's Json field in django admin.
Env Info:
django-version: 3.1.14
Before drive into the widget, this is a simplify version of my model:
class Property(PolymorphicModel):
"""Basic information about property"""
...
address = models.JSONField(blank=True, null=True, default=dict,)
...
And this how I am declaring the form:
class PropertyForm(forms.ModelForm):
class Meta:
model = Property
fields = [
"address",
]
widgets = {
'address': JSONEditorWidget(),
}
I've already manage to convert json file into django admin inputs by using the following code:
class JSONEditorWidget(forms.widgets.Input):
def as_field(self, name, key, value):
""" Render key, value as field """
new_name = name + '__' + key
self.attrs = self.build_attrs({new_name:key})
self.attrs['value'] = utils.encoding.force_text(value)
return u'%s: <input%s />' % (new_name, forms.utils.flatatt(self.attrs))
def to_fields(self, name, json_obj):
"""Get list of rendered fields for json object"""
inputs = []
for key, value in json_obj.items():
inputs.append(self.as_field(name, key, value))
return inputs
def value_from_datadict(self, data, files, name):
"""I've been trying to get new values in this function but nothing successful"""
return json.dumps(prev_dict)
def render(self, name, value, attrs=None, renderer = None):
# TODO: handle empty value (render text field?)
if value is None or value == '':
value = '{}'
json_obj = json.loads(value)
inputs = self.to_fields(name, json_obj)
# render json as well
inputs.append(value)
return utils.safestring.mark_safe(u"<br />".join(inputs))
with this I could go from this:
To this:
My problem now is to catch the new values when user clicks on save/save and continue, so I can convert them into json file to save new records on postgres.
Ive tried with the function value_fromdatadict() but couldn't manage a way to get new values in the input box...
If anyone can helps me I will be so glad, I've been dealing with this a while and this is driving me crazy

GraphQLError Unknown type "XYZMutationInput"

How to create graphql input type for DRF serializer?
I am using django rest framework (DRF) serializers, graphene-django, and I am able to see the CreateThingMutationInput type defined in graphiql:
mutation TestCreate($input: CreateThingMutationInput!) {
createProjectThing(input: $input) {
id
errors {
field
messages
}
}
}
However, I am unable to run:
schema = graphene.Schema(query=Query)
result = schema.execute(self.query, variables=variables)
I get:
[GraphQLError('Unknown type "CreateThingMutationInput".',)]
With the following:
class CreateThingMutation(SerializerMutation):
class Meta:
serializer_class = ThingListViewSerializer
class Mutation(graphene.ObjectType):
debug = graphene.Field(DjangoDebug, name="_debug")
create_project_thing = CreateThingMutation.Field()
I've also tried:
class CreateThingMutationInput(graphene.ObjectType):
input = graphene.Field(convert_serializer_to_input_type(ThingListViewSerializer))
As well as trying to define a:
class Input:
input = graphene.Field(convert_serializer_to_input_type(ThingListViewSerializer))
I can also see the type defined from graphql-codegen in types.d.ts:
export type CreateThingMutationInput = {
id?: Maybe<Scalars['Int']>,
...
}
related:
https://github.com/graphql-python/graphene/issues/531
https://github.com/graphql-python/graphene-django/blob/master/docs/mutations.rst#django-rest-framework
https://github.com/graphql-python/graphene-django/issues/121
I forgot to add the mutation kwarg to:
schema = graphene.Schema(query=Query)
Should be:
schema = graphene.Schema(query=Query, mutation=Mutation)
Another reason this can happen for GraphQLError('Unknown type "Number".',) is if a query function gets an unexpected argument, for example calling getThing with a Number, instead of an ID:
query TestQueryWontWork(id: Number="") {
getThing(id: $id)
}
query TestQueryWorks(id: ID!) {
getThing(id: $id)
}

Mutations - batch creation of objects

I want to use graphene to create many people in one go.
The document only mention the way to create one person like this:
class CreatePerson(graphene.Mutation):
class Input:
name = graphene.String()
age = graphene.Int()
ok = graphene.Boolean()
person = graphene.Field(lambda: Person)
#staticmethod
def mutate(root, args, context, info):
person = Person(name=args.get('name'), age=args.get('age'), mobile=args.get('mobile'))
ok = True
return CreatePerson(person=person, ok=ok)
are there any ways to get it done?
Instead of using a mutation that creates a list of objects, you can also call a mutation that creates one objects multiple times in one GraphQL request. This is accomplished using GraphQL Aliases:
mutation {
c001: createPerson(
name: "Donald Duck"
age: 42
) {
id
}
c002: createPerson(
name: "Daisy Duck"
age: 43
) {
id
}
c003: createPerson(
name: "Mickey Mouse"
age: 44
) {
id
}
}
I can figure out a solution base on the answer of Jan Hančič
There is a type called graphene.InputObjectType to use in this case
The solution can be
class PersonInput(InputObjectType):
name = graphene.String()
age = graphene.Int()
class CreatePeople(graphene.Mutation):
class Input:
people = graphene.List(PersonInput)
people = graphene.List(lambda: Person)
#staticmethod
def mutate(root, args, context, info):
people = [Person.objects.create(name=person.name, age=person.age) for person in args.get('people')]
return CreatePeople(people=people)
Make your mutation input a list and return a list of created people. Something like this:
class CreatePerson(graphene.Mutation):
class Input:
name = graphene.List(graphene.String)
ok = graphene.Boolean()
people = graphene.List(Person)
#staticmethod
def mutate(root, args, context, info):
people = [Person(name=name) for name in args.get('name)]
ok = True
return CreatePerson(people=people, ok=ok)
Receive a list of input, create all instances and return them all
The model node/type should be like-
class UserType(DjangoObjectType):
class Meta:
model = User
interfaces = (CustomGrapheneNode, )
filter_fields = {}
only_fields = (
'name',
'email'
)
Define Input fields
class UserInput(graphene.InputObjectType):
name = graphene.String(required=True)
password = graphene.String(required=True)
Mutation class
class CreateUser(graphene.Mutation):
users = graphene.List(UserType)
class Input:
data = graphene.List(UserInput)
Output = graphene.List(UserType)
def mutate(self, info, data):
users = []
for item in data:
user = User.objects.create(name=data['name'],
password=data['password'])
users.append(user)
return users
make this mutation callable by main schema
class Mutation():
create_user = CreateUser.Field()
the Mutation Query view will be as -
mutation{
createUser(data:[{name:"john", password:"1234"},
{name:"john", password:"1234"}]) {
user{
name
}
}
}

Django AJAX call: Referencing Table in JS

Is there a way I can reference a list containing data from my database (item_list = inventory.objects.order_by('name')) in my jquery AJAX call?
This is my code:
/models.py:
class phonebook(models.Model):
name = models.Charfield(max_length=200)
phone_number = models.CharField(max_length=100)
/views.py:
def phonebook_home(request):
global phonebook
phonebook = phonebook.objects.order_by('name')
def get_next_3_contacts(request):
returnedContacts = phonebook[contactIndex:contactIndex+3]
return HttpResponse(phonebook)
/main.js:
var = ajax_call {
type: 'GET'
url: DEFINED_URL
data: {
index: contactIndex
},
dataType: 'html'
success: function (returned, textStatus_ignored, jqXHR_ignored) {
var contactIndex = 0
function phonebook_list(name, phone_number) {
"<li>" + name + " : " + phone_number + "</li>"
}
for(var index=0; index < 3; index++) {
var name = phonebook[index].name
var phone_number = phonebook[index].phone_number
$("ul").append(phonebook_list(name, phone_number))
}
contactIndex += 3
}
The phonebook[index].name / .phone_number returns "undefined" on my page. I want to keep my js file separate from my template file as it will be easier for me to debug, but unfortunately, this problem has stumped me. I also inputted an alert to test out if any data was being returned from the data base, which only returns a string containing the names of the contacts with no spacing in between contact names. Ex: "JaredSarahJohn".
All help and any bit of advice is appreciated!
A couple of things need to be cleaned up in order for this solution to work:
Your idea that global phonebook will be available from within get_next_3_contacts() is incorrect. When you make the AJAX call that will ultimately invoke get_next_3_contacts() the variable phonebook is no longer available. It went out of scope when the call to phonebook_home() completed.
What's the solution? Change phonebook_home() to accept an offset and count parameters. Have it hit the database and return the requested quantities. This is called pagination and is something you should get familiar with!
def phonebook_home(request, offset, count):
phonebook = phonebook.objects.all()[offset:offset+count]
But how do we get those results down to your AJAX handler? You can't just "return" a list of objects to the HTTPResponse() function - it's looking for text to render, not Model objects.
import json
from django.http import JsonResponse
def phonebook_home(request, offset, count):
status = "OK"
return_data = ""
try:
phonebook = phonebook.objects.all()[offset:offset+count]
return_data = json.dumps(phonebook)
exception:
status = "UH OH"
return JsonResponse({'data': return_data, 'status': status)

There are many similar dao methods in anorm, is it right?

I'm using Play2 with anorm. I think the spirit of anorm is write plain sqls, no magic behind.
But I quickly found I have write a lot of similar dao methods. For example:
case class User(id:Pk[String], username:String, email:String, realname:String, city:String, website:String)
object User {
val simple = get[Pk[String]]("id") ~ get[String]("username") ~ ... get[String]("website") map {
case id ~ username ~ ... ~ website = User(id, username, ..., website)
}
def findByUsername(username:String) = DB.withConnection { implicit connection =>
SQL("select * from users where username={username}").on('username->username).as(simple.singleOpt)
}
def findByEmail(email:String) = DB.withConnection { implicit connection =>
SQL("select * from users where email={email}").on('email->email).as(simple.singleOpt)
}
def findById(id:String) = DB.withConnection { implicit connection =>
SQL("select * from users where id={id}").on('id->id).as(simple.singleOpt)
}
def findByRealname(keyword:String) = DB.withConnection { implicit connection =>
SQL("select * from users where realname like {keyword}").on('keyword->"%"+keyword+"%").as(simple *)
}
// more similar methods
}
There methods are almost the same, exception the where clause has small difference.
So I created a findWhere() method as:
def findWhere(conditon, values:Any*) = ...
That I can call it in actions:
User.findWhere("id=?", id)
User.findWhere("username=?", username)
It works, but I don't think it's recommended by anorm.
What's the best way to solve this problem?
Why do you believe it is not recommended or ok?
Anorm only cares of receiving a SQL query and parsing the result into a case class. If due to your constraints/design you generate that SQL request dinamically, that makes no difference.
The only issue I see is witht he '?' char, which is nto the way Anorm works. I believe it would me more like:
User.findWhere("username", username)
def findWhere(field: String, value: String) = {
SQL("select * from users where "+ field +"={"+ field +"}").on(Symbol(field)->value).as(simple.singleOpt)
}
This is a simple example, extend as required.

Resources