django tastypie update two models

核能气质少年 提交于 2019-12-21 05:51:32

问题


I have a problem with tastypie regarding updates to two models with one (POST) api call.

We have two models, an user model and a candidate model which references the user model. We want to publish the candidate model via the api interface, but want to hide the user model. So, as a first step I merge the user model fields with the candidate model fields in the dehydrate process. This is working completly fine.

The problem is, that I can't figure out, how to do it the other way round (hydrate and create both models. we need to create a seperate user model and cant just merge both models)


回答1:


Would be nice if you showed us some code and what have you tried, but for this kind of task you should probably override the obj_create(...) method of tastypie.resources.ModelResource class.

It looks like this:

    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

So in your resource you could have something like:

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 )

And this should get you started. If you have any trouble, please ask a question and provide some code.



来源:https://stackoverflow.com/questions/12264949/django-tastypie-update-two-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!