【问题标题】:Calculate a value from GraphQL and save it in Django models从 GraphQL 计算一个值并将其保存在 Django 模型中
【发布时间】:2020-03-17 04:19:58
【问题描述】:

我正在尝试从 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

附:抱歉英语不好。谢谢!

【问题讨论】:

  • function_name,这个字段是什么?
  • 随机函数的字段,我觉得这个字段没那么重要

标签: python django django-models graphql graphene-python


【解决方案1】:

我不知道您为什么将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 方法在数据库中创建记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多