Python 从GraphQL计算一个值,并将其保存在Django模型中

Python 从GraphQL计算一个值,并将其保存在Django模型中,python,django,django-models,graphql,graphene-python,Python,Django,Django Models,Graphql,Graphene Python,我试图从GraphQL计算一个值。我正在向Django模型发送变异,但在保存它之前,我想用if语句计算这个值(如果值大于10除以2,如果小于10乘以2) 我不知道在哪里添加这个函数 这是我在schema.py中的变异 class CreatePrice(graphene.Mutation): price = graphene.Field(PriceType) class Arguments: price_data = PriceInput(required=Tr

我试图从GraphQL计算一个值。我正在向Django模型发送变异,但在保存它之前,我想用if语句计算这个值(如果值大于10除以2,如果小于10乘以2)

我不知道在哪里添加这个函数

这是我在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) 
这是我的Django模型。基价是计算值,函数名有两个选项(*2或/2,取决于初始值)


顺便说一句,很抱歉英语不好。谢谢

我不知道你为什么要用
CharField
作为
base\u价格
。因此,我建议您这样做:

@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)

您也可以通过创建对象并在数据库上使用
保存
方法在数据库中创建记录。

函数名
,这个字段是什么?对于随机函数,我认为这个字段不太重要
@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)