【问题标题】:manage create method of django when there are lots of fields当有很多字段时管理 django 的创建方法
【发布时间】:2019-06-30 04:13:57
【问题描述】:

我正在开发我在后端使用 django 的项目。我有一个与用户相关的模型调用配置文件。配置文件模型有超过 10 个字段,当尝试更新用户配置文件时,我更新所有这些字段的代码将是这样的

class UpdateProfile(graphene.Mutation):
    class Arguments:
        input = types.ProfileInput(required=True)

    success = graphene.Boolean()
    errors = graphene.List(graphene.String)
    profile = graphene.Field(schema.ProfileNode)

    @staticmethod
    def mutate(self, info, **args):
        is_authenticated = info.context.user.is_authenticated
        data = args.get('input')
        if not is_authenticated:
            errors = ['unauthenticated']
            return UpdateProfile(success=False, errors=errors)
        else:
            profile = Profile.objects.get(user=info.context.user)
            profile = models.Profile.objects.get(profile=profile)
            profile.career = data.get('career', None)
            profile.payment_type = data.get('payment_type', None)
            profile.expected_salary = data.get('expected_salary', None)
            profile.full_name = data.get('full_name', None)
            profile.age = data.get('age', None)
            profile.city = data.get('city', None)
            profile.address = data.get('address', None)
            profile.name_of_company = data.get('name_of_company', None)
            profile.job_title = data.get('job_title', None)
            profile.zip_code = data.get('zip_code', None)
            profile.slogan = data.get('slogan', None)
            profile.bio = data.get('bio', None)
            profile.website = data.get('website', None)
            profile.github = data.get('github', None)
            profile.linkedin = data.get('linkedin', None)
            profile.twitter = data.get('twitter', None)
            profile.facebook = data.get('facebook', None)
            profile.image=info.context.FILES.get(data.get('image', None))
            profile.save()
            return UpdateProfile(profile=profile, success=True, errors=None)

所以我的问题是,假设如果有超过 20、30 个字段,您将如何设计更新这些字段的代码? (仅考虑视图部分)

【问题讨论】:

    标签: python django design-patterns


    【解决方案1】:

    您可以为从前端获得的任何值创建一个 kwargs(意味着字典),然后您可以解压缩这些值。如果您不知道,您可以打开包装概念。

    假设 kwargs 是您的字典,而您只想更新 career 和 payment_type。

    kwargs = {}
    
    kwargs['carrer'] = data.get('career', None)
    kwargs['payment_type'] = data.get('payment_type', None)
    
    Profile.objects.filter(user=info.context.user).update(**kwargs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 2018-11-26
      • 1970-01-01
      • 2014-10-20
      • 2014-10-12
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多