【问题标题】:django tastypie update two modelsdjango sweetpie 更新两个模型
【发布时间】:2012-09-04 13:49:55
【问题描述】:

我有一个关于通过一个 (POST) api 调用更新两个模型的问题。

我们有两个模型,一个用户模型和一个引用用户模型的候选模型。我们想通过 api 接口发布候选模型,但想隐藏用户模型。因此,作为第一步,我将用户模型字段与脱水过程中的候选模型字段合并。这工作得很好。

问题是,我不知道如何反过来做(水合并创建两个模型。我们需要创建一个单独的用户模型,不能只合并两个模型)

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    如果您向我们展示一些代码以及您尝试过的方法会很好,但对于此类任务,您可能应该覆盖 tastypie.resources.ModelResource 类的 obj_create(...) 方法。

    看起来像这样:

        def obj_create(self, bundle, request=None, **kwargs):
            """
            A ORM-specific implementation of ``obj_create``.
            """
            bundle.obj = self._meta.object_class()
    
            for key, value in kwargs.items():
                setattr(bundle.obj, key, value)
    
            bundle = self.full_hydrate(bundle)
    
            # Save FKs just in case.
            self.save_related(bundle)
    
            # Save the main object.
            bundle.obj.save()
    
            # Now pick up the M2M bits.
            m2m_bundle = self.hydrate_m2m(bundle)
            self.save_m2m(m2m_bundle)
            return bundle
    

    所以在你的资源中你可以有类似的东西:

    from tastypie.resources import ModelResource
    
    class MyResource( ModelResource ):
    
        def obj_create( self, bundle, request = None, **kwargs ):
            # ...
            # create User instance based on what's in the bundle
            # user = ...
            # ...
            # kwargs[ 'user' ] = user < will be set on Candidate instance in super()
            # ...
    
            # call super, resulting in creation of the Candidate model
            super( MyResource, self ).obj_create( self, bundle, request, **kwargs )
    

    这应该可以帮助您入门。如果您有任何问题,请提出问题并提供一些代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多