Graphene Django - Mutation with one to many relation foreign key

后端 未结 1 1080
孤街浪徒
孤街浪徒 2021-02-07 20:44

I would like to know how to properly create mutation for creating this django model:

class Company(models.Model):

    class Meta:
        db_table = \'companies         


        
1条回答
  •  孤街浪徒
    2021-02-07 21:08

    For those, which are still searching for the answer.

    class CompanyInput(graphene.InputObjectType):
        name = graphene.String(required=True)
        email = graphene.String(required=True)
        address = graphene.String(required=True)
        crn = graphene.String(required=True)
        tax = graphene.String(required=True)
        currency = graphene.Field(CurrencyInput)
        country = graphene.Field(CountryInput)
        parent = graphene.Field(CompanyInput)
        phone_number = graphene.String()
    
    class CurrencyInput(graphene.InputObjectType):
        name = graphene.String()
        code = graphene.String()
        character = graphene.String()
    
    class CountryInput(graphene.InputObjectType):
        name = graphene.String()
        code = graphene.String()
    
    
    class CreateCompany(graphene.Mutation):
        company = graphene.Field(CompanyType)
    
        class Arguments:
            company_data = CompanyInput(required=True)
    
        @staticmethod
        def mutate(root, info, company_data):
            company = Company.objects.create(**company_data)
            return CreateCompany(company=company)
    

    As you can see, I just replaced CompanyType, CurrencyType and CountryType objects for input objects because Input objects specifying INPUT which user type to query (request).

    Type objects specifying return object which mutation returns, when everything was successfully. So when you just look at class CreateCompany, company is object which will be returned when mutation is success (Is CompanyType object) because we creating company and we wants response of object company.

    As Arguments class there is CompanyInput which has nested inputs like currency or country or self (its like object in object).

    Static method mutate will call Django create function and this created object will be assigned to our company object which is CompnyType and this will be that response.

    (Of course you can call another function than create when you want to implement some business logic before and after creating but mutation method must return specific object or objects which was or were defined as response. For me company in CreateCompany class. Of course there can be more objects or lists of objects. It only depends on you.)

    0 讨论(0)
提交回复
热议问题