本文介绍了在Django Tastypie API中包含子资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在计划一个使用Django和Tastypie进行REST API的站点,而
我有一个艰难的时刻,想出了一个正确的方式,在返回的资源中包含
子资源。



作为一个沙箱,我制作了一个小型应用程序,其中包含一个Ticket模型和一个TicketComment
模型,其中注释属于一张票。我看了一下关于嵌套资源(http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources),
的Tastypie Cookbook
食谱,但我有一个很难理解为什么我应该这样做。
下面的代码使用django.forms.models.model_to_dict()来获取票据
中的注释,但我认为这里有一个gotcha。



有没有理由我不应该做我现在在做什么?此外,还有一个
清洁剂的感觉模式比食谱中列出的那样?



模型如下:

 #ticket / 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',正在进行中),
('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,)

资源如下:

 #ticket / api.py 

from tastypie import fields
from tastypie.resources import ModelResource
从ticket.models导入Ticket,TicketComment
从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是第一个评论。,
commenter_email:[email protected]
id:1,
票:1
},
{
评论:这是第二个评论,
commenter_email:[email protected]
id:2,
票:1
}
],
create_ts:2011-10-17T15:55:11.372000,
描述:这是第一张票,
id:1,
优先:M,
resource_uri:/ api / v1 / ticket / 1 /,
status:NEW,
submitter_email:[email protected]
标题:第一票
}


解决方案

您正在寻找相关字段:


I'm planning a site with Django and Tastypie for the REST API, andI'm having a tough time figuring out the "right" way to includechild resources in a returned resource.

As a sandbox, I made a small app with a Ticket model and a TicketCommentmodel, where comments belong to a ticket. I looked at the Tastypie Cookbookrecipe on nested resources (http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources),but I'm having a hard time understanding why I should do that. The code belowuses django.forms.models.model_to_dict() to get the comments into the ticket,but I'm thinking there must be a "gotcha" here somewhere.

Is there a reason I shouldn't do what I'm doing now? Also, is there acleaner-feeling pattern for this than what's listed in the cookbook?

Models are as follows:

# 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,)

Resources are as follows:

# 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'

Output is as follows:

{
   comments: [
        {
            comment: "This is the first comment.",
            commenter_email: "[email protected]",
            id: 1,
            ticket: 1
        },
        {
            comment: "This is the second comment.",
            commenter_email: "[email protected]",
            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: "[email protected]",
    title: "First Ticket"
}
解决方案

You're looking for related fields: http://django-tastypie.readthedocs.org/en/latest/fields.html#relationship-fields

这篇关于在Django Tastypie API中包含子资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 11:10