I am trying to have a graphql mutation create the inputs for two django models at once using strawberry. I check the docs here and there were no examples of how to do this.
I have the following django model:
class Address(models.Model):
name = models.CharField()
class Person(models.Model):
name = models.CharField()
address = models.ForeignKey('Address', on_delete=models.CASCADE, blank=False, null=False)
With they type.py
@strawberry.django.type(models.Address)
class Address:
id: auto
name:auto
@strawberry.django.input(models.Address)
class AddressInput:
id: auto
name:auto
@strawberry.django.type(models.Person)
class Person:
id: auto
name: auto
address:'Address'
@strawberry.django.input(models.Person)
class Person:
id: auto
name: auto
address:'AddressInput'
For the schema.py
I have:
@strawberry.type
class Mutation:
createAddress: Address = mutations.create(AddressInput)
createPerson: Person =mutations.create(PersonInput)
schema = strawberry.Schema(mutation=Mutation)
I tried the Mutation but got an error:
mutation newPerson ($name: String!, $addressname:String!){
createPerson(data: {name: $name, address: {name: $addressname}}) {
id
name
address {
id
name
}
}
}
#Query Variables
{
"name": "Min",
"addressname": "jkkihh",
}
Error message:
"message": "Field 'id' expected a number but got PersonInput(id=<strawberry.unset._Unset object at 0x00000194FB945C90>, addressname='jkkihh', description=<strawberry.unset._Unset object at 0x00000194FB945C90>, notes=<strawberry.unset._Unset object at 0x00000194FB945C90>)."
This is similar the this question I previously asked using graphene. Where it was resolved by making an new object type to store and wrote a mutate function inside a class for mutation. I also tried doing two mutations but had issues getting the id for the foreign key address when it was created.
CodePudding user response:
I think strawberry_django has a bug here, though you should prefer using the strawberry_django_plus package because it is more maintained, hopefully it will be merged to the official strawberry soon.
In your case it would be:
from strawberry_django_plus import gql
from strawberry import auto
@gql.django.type(models.Person)
class Person:
id: auto
name: auto
address:'Address'
@gql.django.input(models.Person)
class Person:
id: auto
name: auto
address:'AddressInput'
@gql.type
class Mutation:
createAddress: Address = gql.django.create_mutation(AddressInput)
createPerson: Person = gql.django.create_mutation(PersonInput)
schema = strawberry.Schema(mutation=Mutation)