django-tastypie:将 ModelResource 链接到资源

发布于 2024-12-08 14:09:53 字数 2007 浏览 1 评论 0原文

我目前正在尝试 django-tastypie 设计一个 RESTful api。我面临一个问题:

# the RevisionObject retrieve commits info through pysvn
# This Resource is fully functionnal (RevisionObject code is not here)
class RevisionResource(Resource):
    id = fields.CharField(attribute='revision')
    description = fields.CharField(attribute='message')
    author = fields.CharField(attribute='author')
    changed_path = fields.ListField(attribute='changed_paths')

    class Meta:
        object_class = RevisionObject
        allowed_methods = ['get']
        resource_name = 'revision'

class RevisionToApplyResource(ModelResource):
    #### here's the problem
    revision = fields.ToManyField(RevisionResource, 'revision')
    ####
    class Meta:
        queryset = RevisionToApply.objects.all()

在我的 models.py 中,我有:

class RevisionToApply(models.Model):
    patch = models.ForeignKey(PatchRequest)
    revision = models.PositiveIntegerField()
    applied = models.BooleanField(default = False)

我的问题是 RevisionToApply 模型(对于 django)使用 int 进行修订。

我如何告诉 tastypie 使用 RevisionToApplyResource 的修订字段作为指向 RevisionResource 的指针?如果 ToXxxxField 仅用于与 django 模型链接,那么插入 ResourceObject 的最佳时机是什么?

谢谢。

class NoForeignKeyToOneField(ToOneField):
    def dehydrate(self, bundle):
        try:
            obj_key = getattr(bundle.obj, self.attribute)
            foreign_obj = self.to_class().obj_get(pk=obj_key)
        except ObjectDoesNotExist:
            foreign_obj= None

        if not foreign_obj:
            if not self.null:
                raise ApiFieldError("The model '%r' has an empty attribute"
                   "'%s' and doesn't allow null value." % (bundle.obj,
                   self.attribute))
            return None

        self.fk_resource = self.get_related_resource(foreign_obj)
        fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
        return self.dehydrate_related(fk_bundle, self.fk_resource)

I'm currently trying django-tastypie to design a RESTful api. I'm facing a problem:

# the RevisionObject retrieve commits info through pysvn
# This Resource is fully functionnal (RevisionObject code is not here)
class RevisionResource(Resource):
    id = fields.CharField(attribute='revision')
    description = fields.CharField(attribute='message')
    author = fields.CharField(attribute='author')
    changed_path = fields.ListField(attribute='changed_paths')

    class Meta:
        object_class = RevisionObject
        allowed_methods = ['get']
        resource_name = 'revision'

class RevisionToApplyResource(ModelResource):
    #### here's the problem
    revision = fields.ToManyField(RevisionResource, 'revision')
    ####
    class Meta:
        queryset = RevisionToApply.objects.all()

In my models.py I have:

class RevisionToApply(models.Model):
    patch = models.ForeignKey(PatchRequest)
    revision = models.PositiveIntegerField()
    applied = models.BooleanField(default = False)

My problem is that the RevisionToApply models (for django) uses an int to the revision.

How can I tell tastypie to use the revision field of RevisionToApplyResource as a pointer to a RevisionResource? If the ToXxxxField are only for linking with django models, what is the perfect moment to insert the ResourceObject?

thanks.

class NoForeignKeyToOneField(ToOneField):
    def dehydrate(self, bundle):
        try:
            obj_key = getattr(bundle.obj, self.attribute)
            foreign_obj = self.to_class().obj_get(pk=obj_key)
        except ObjectDoesNotExist:
            foreign_obj= None

        if not foreign_obj:
            if not self.null:
                raise ApiFieldError("The model '%r' has an empty attribute"
                   "'%s' and doesn't allow null value." % (bundle.obj,
                   self.attribute))
            return None

        self.fk_resource = self.get_related_resource(foreign_obj)
        fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
        return self.dehydrate_related(fk_bundle, self.fk_resource)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

渡你暖光 2024-12-15 14:09:53

我就是这样做的。看一下 ToOneField 类的工作原理,您会注意到水合/脱水方法对负责获取和设置实际的相关实例。通过子类化 ToOneField 并重写这两个方法,您无需实际外键即可获得 Tastypie 的自动化资源处理的优势。

(我指的是 ToOneField 而不是 ToManyField,因为在您的模型中,给定的 RevisionToApply 似乎只能指向一个修订版。)

它看起来像这样:

class NoForeignKeyToOneField(ToOneField):

    def dehydrate(self, bundle):
        # Look up the related object manually
        try:
            obj_key = getattr(bundle.obj, self.attribute)
            ###
            # Get the revision object here. If you want to make it generic,
            # maybe pass a callable on __init__ that can be invoked here
            ###
            foreign_obj = revision_object
        except ObjectDoesNotExist:
            foreign_obj = None
        # The rest remains the same
        if not foreign_obj:
            if not self.null:
                raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (bundle.obj, self.attribute))
            return None

        self.fk_resource = self.get_related_resource(foreign_obj)
        fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
        return self.dehydrate_related(fk_bundle, self.fk_resource)

    def hydrate(self, bundle):
        value = super(NoForeignKeyToOneField, self).hydrate(bundle)

        if value is None:
            return value

        # Here, don't return the full resource, only the primary key
        related_resource = self.build_related_resource(value, request=bundle.request)
        return related_resource.pk

然后在资源中使用此字段类型,而不是基本的 ToOneField。我还没有测试过它,但我相信这个方法是合理的、简单的,并且它会完成工作。

Here's how I would do it. Taking a look at how the ToOneField class works, you'll notice that the hydrate/dehydrate method pair takes care of getting and setting the actual related instance. By subclassing ToOneField and overriding these two methods, you can get the benefit of Tastypie's automated resource handling without an actual foreign key.

(I'm referring to ToOneField rather than ToManyField because in your model, a given RevisionToApply can only point to one revision, it seems.)

It would look something like this:

class NoForeignKeyToOneField(ToOneField):

    def dehydrate(self, bundle):
        # Look up the related object manually
        try:
            obj_key = getattr(bundle.obj, self.attribute)
            ###
            # Get the revision object here. If you want to make it generic,
            # maybe pass a callable on __init__ that can be invoked here
            ###
            foreign_obj = revision_object
        except ObjectDoesNotExist:
            foreign_obj = None
        # The rest remains the same
        if not foreign_obj:
            if not self.null:
                raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (bundle.obj, self.attribute))
            return None

        self.fk_resource = self.get_related_resource(foreign_obj)
        fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
        return self.dehydrate_related(fk_bundle, self.fk_resource)

    def hydrate(self, bundle):
        value = super(NoForeignKeyToOneField, self).hydrate(bundle)

        if value is None:
            return value

        # Here, don't return the full resource, only the primary key
        related_resource = self.build_related_resource(value, request=bundle.request)
        return related_resource.pk

And then use this field type in your resource rather than the basic ToOneField. I haven't tested it , but I believe the approach is sound, simple and it'll get the job done.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文