Search code examples
pythondjangodjango-modelsgraphqlgraphene-python

Calculate a value from GraphQL and save it in Django models


I am trying to calculate a value from GraphQL. I am sending mutation to Django models but before save it I want to calculate this value with if statement (if the value is greater than 10 divide by 2, if is less than 10 multiply by 2).

I don't know where to add this function.

Here is my mutation in schema.py

class CreatePrice(graphene.Mutation):
    price = graphene.Field(PriceType)

    class Arguments:
        price_data = PriceInput(required=True)

    @staticmethod
    def mutate(root, info, price_data):
        price = Price.objects.create(**price_data)
        return CreatePrice(price=price)

class Mutation(graphene.ObjectType):
    create_product = CreateProduct.Field()
    create_price = CreatePrice.Field()

schema = graphene.Schema(query = Query, mutation=Mutation) 

And here is my Django model. Base price is calculated value and function name has two options(*2 or /2 it depends of initial value).

class Price(models.Model):
    base_price = models.CharField(max_length = 20)
    function_name = models.CharField(max_length = 20, choices = PROMO_FUNCTION)

    def __str__(self):
        return self.price_name

P.S. Sorry for bad English. Thanks!


Solution

  • I don't know why you are using CharField for base_price. So, I suggest you to do this:

    @staticmethod
    def mutate(root, info, price_data):
        if int(price_data.base_price) >= 10:
            price_data.base_price = str(int(price_data.base_price) / 2)
        else:
            price_data.base_price = str(int(price_data.base_price) * 2)
        price = Price(base_price=price_data.base_price, function_name=price_data.function_name)
        price.save()
        return CreatePrice(price=price)
    

    You can also create records in database by creating object and using save method on it.