从GraphQL计算值并将其保存在Django模型中

问题描述 投票:2回答:1

我正在尝试从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,取决于初始值)。

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。对不起,英语不好。谢谢!

python django django-models graphql graphene-python
1个回答
0
投票

我不知道您为什么将CharField用于base_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)

您还可以通过创建对象并对其使用save方法来在数据库中创建记录。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.