gpt4 book ai didi

python - 在 Django Tastypie API 中包含子资源

转载 作者:太空狗 更新时间:2023-10-29 20:44:15 24 4
gpt4 key购买 nike

我正计划使用 Django 和 Tastypie 为 REST API 创建一个站点,并且我很难找出“正确”的方式来包括返回资源中的子资源。

作为沙箱,我制作了一个带有 Ticket 模型和 TicketComment 的小应用模型,其中评论属于工单。我看了 Tastypie 食谱嵌套资源的食谱(http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources),但我很难理解为什么我应该这样做。下面的代码使用 django.forms.models.model_to_dict() 将评论添加到工单中,但我认为这里一定有一个“陷阱”。

有什么理由让我不应该做我现在正在做的事情吗?另外,有没有比食谱中列出的更干净的感觉模式?

模型如下:

# tickets/models.py

from django.db import models

class Ticket(models.Model):
title = models.CharField(max_length=200)
create_ts = models.DateTimeField(auto_now_add=True)
submitter_email = models.EmailField()
PRIORITY_CHOICES = (
('H', 'High'),
('M', 'Medium'),
('L', 'Low'),)
priority = models.CharField(max_length=1, choices=PRIORITY_CHOICES)
description = models.TextField()
STATUS_CHOICES = (
('NEW', 'New & Unclaimed'),
('WIP', 'Work In Progress'),
('RES', 'Resolved'),
('CLS', 'Closed'),)
status = models.CharField(max_length=3, choices=STATUS_CHOICES)

def __unicode__(self):
return "<Ticket:%d:%s>" % (self.id, self.title,)

class TicketComment(models.Model):
ticket = models.ForeignKey(Ticket)
comment_ts = models.DateTimeField(auto_now_add=True)
commenter_email = models.EmailField()
comment = models.TextField()

def __unicode__(self):
return "<TicketComment:%d:%d>" % (self.ticket.id, self.id,)

资源如下:

# tickets/api.py

from tastypie import fields
from tastypie.resources import ModelResource
from tickets.models import Ticket, TicketComment
from django.forms.models import model_to_dict

class TicketResource(ModelResource):

class Meta:
queryset = Ticket.objects.all()
resource_name = 'ticket'

def dehydrate(self, bundle):
comments = TicketComment.objects.filter(ticket=bundle.data['id'])
bundle.data['comments'] = [model_to_dict(c) for c in comments]
return bundle

class TicketCommentResource(ModelResource):
ticket = fields.ForeignKey(TicketResource, 'ticket')

class Meta:
queryset = TicketComment.objects.all()
resource_name = 'comment'

输出如下:

{
comments: [
{
comment: "This is the first comment.",
commenter_email: "me@example.com",
id: 1,
ticket: 1
},
{
comment: "This is the second comment.",
commenter_email: "me@example.com",
id: 2,
ticket: 1
}
],
create_ts: "2011-10-17T15:55:11.372000",
description: "This is the first ticket.",
id: "1",
priority: "M",
resource_uri: "/api/v1/ticket/1/",
status: "NEW",
submitter_email: "me@example.com",
title: "First Ticket"
}

最佳答案

关于python - 在 Django Tastypie API 中包含子资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7815756/

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