【问题标题】:How to declare child resources in Tastypie?如何在 Tastypie 中声明子资源?
【发布时间】:2014-01-14 19:05:07
【问题描述】:

我有这个models.py:

from django.db import models

class Item(models.Model):
    text = models.TextField()

class Note(models.Model):
    text = models.TextField()
    items = models.ManyToManyField(Item)

还有这个api.py:

import tastypie
from tastypie.resources import ModelResource
from tastypie.api import Api
from main.models import Item, Note

class ItemResource(ModelResource):
    class Meta:
        resource_name = 'items'
        queryset = Item.objects.all()

class NoteResource(ModelResource):
    items = tastypie.fields.ToManyField(ItemResource, 'items', full=True)

    class Meta:
        resource_name = 'notes'
        queryset = Note.objects.all()

api = Api(api_name='v1')
api.register(NoteResource())

我希望项目的唯一端点是:

/api/v1/notes/4/items

/api/v1/notes/4/items/2

没有/api/v1/items/?note=4

我一直在阅读 Tastypie 文档,但没有找到任何相关信息。

This 文档推荐我在此处发布的 URL 表单。

我怎样才能做到这一点?

【问题讨论】:

  • 您可能想查看django-rest-framework.org
  • @orokusaki 好的,我读了很多。它看起来比 Tastypie 好得多。你能指出我用restframework做这件事的正确方向吗?
  • 我刚刚为您添加了一个包含更多信息的答案。

标签: python django api rest tastypie


【解决方案1】:

使用Django REST Framework(后人,见cmet on OP),子资源声明如下(简单示例):

class AddressSerializer(ModelSerializer):
    """
    A serializer for ``Address``.
    """
    class Meta(object):
        model = Address


class OrderSerializer(ModelSerializer):
    """
    A serializer for ``Order``.
    """
    address = AddressSerializer()

    class Meta(object):
        model = Order

要开始使用,我强烈建议您只需关注this tutorial。在自定义 URL、自定义序列化输出等方面,它将为您提供 100% 的需求。

Tasty pie 是一个很棒的项目,而创建者 Daniel Lindsley 是一个非常聪明的人(我曾与他合作过一段时间),但就像其他所有伟大的项目一样,有人出现并让我们大吃一惊具有learned from the good and bad parts of the existing framework 的新事物。

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2020-03-17
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多