gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:18 24 4
gpt4 key购买 nike

我有这个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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com