python - 如何在 Tastypie 中声明子资源?

标签 python django api rest tastypie

我有这个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 (后人,请参阅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% 的所需内容。

Tastypie 是一个伟大的项目,创作者 Daniel Lindsley 是一个非常聪明的人(我和他一起工作过一段时间),但就像其他所有伟大的项目一样,有人出现并让我们大吃一惊一些新的东西有 learned from the good and bad parts of the existing framework .

关于python - 如何在 Tastypie 中声明子资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21121834/

相关文章:

python - 为空数据框创建异常

python - 从列表中删除整数+python

python - 决策树总是返回完美的准确性

django - 了解 Django 的服务器控制台输出

python - Django - ModelChoiceField - TypeError - __init__() 至少需要 2 个参数(给定 1 个)

Black Hat Python 书中的 Python 嗅探

javascript 文件中的 Django {% static 'path' %}

c# - 无法使用C#函数从Json文件读取多个值

objective-c - 在 REST Api 中建模对象继承

api - 如何使用 Dio 在 Flutter 中调用 API?