将方法添加到Django模型

时间:2017-07-21 17:46:47

标签: python django graphql

我构建了我的第一个GraphQL突变。最初我使用我找到的示例代码构建它。但现在我重构它是为了更好的结构。虽然代码似乎工作正常,因为我对Django来说相对较新,但我不确定我使用的方法是Django / Python的最佳实践。

这是我的相关代码:



#models.py

class Workflow(models.Model):
    name = models.CharField(max_length=30)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return "{}".format(self.name)

    @classmethod
    def create(cls, name, description):
        new_workflow = cls(
            name = name,
            description = description
        )
        
        new_workflow.save()
        return new_workflow






# mutations.py

class Workflow(DjangoObjectType):
    class Meta:
        model = WorkflowModel
        interfaces = (relay.Node, )

    @classmethod
    def get_node(cls, id, context, info):
        node = get_workflow(id)
        return node


class CreateWorkflow(relay.ClientIDMutation):
    class Input:
        name = graphene.String()
        description = graphene.String()

    workflow = graphene.Field(Workflow)
    success = graphene.Boolean()
    errors = graphene.String()

    @classmethod
    def mutate_and_get_payload(cls, input, context, info):
        name = input.get('name')
        description = input.get('description')

        try:
            workflow = WorkflowModel.create(name, description)
            return CreateWorkflow(workflow=workflow, success=True)

        except Exception as e:
            success = False
            return CreateWorkflow(workflow=None, success=False, errors=str(e))


class Mutation(graphene.AbstractType):
    create_workflow = CreateWorkflow.Field()




我的主要问题与我将def create引入Django Workflow模型的方式有关。这是正确的方法吗?

罗伯特

1 个答案:

答案 0 :(得分:0)

您无需在Django中的模型类中创建“create”方法。您可以创建一个调用其init方法或使用Class.objects.create()的新对象。所以你可以拥有:

models.py

class Workflow(models.Model):
    name = models.CharField(max_length=30)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return "{}".format(self.name)

然后创建一个“工作流程”,您可以使用:

new_obj = Workflow(name="wf name", description="wf description")
new_obj.save()

或者

Workflow.objects.create(name="wf name",description="wf description)

通常,您可以创建新的类方法或覆盖现有的方法以满足其他需求。 E.g:

class Workflow(models.Model):
    name = models.CharField(max_length=30)
    description = models.TextField(blank=True, null=True)
    deleted = models.DateTimeField(blank=True, null=True)

    @property
    def short_description(self):
        if self.description:
            return "%s..." % self.description[:20]

    # ovewriting the superclass' delete method  
    def delete(self):
        self.deleted = timezone.now()
        self.save()

    def __str__(self):
        return "{}".format(self.name)