0

我对 Django 和 Django sweetpie 比较陌生,所以我的问题可能很简单。

我正在尝试为可本地化的文本实现一个 RESTFUL 服务。

我的 Django 资源是:

#The different languages
class Language(models.Model):
    abbreviation = models.CharField(max_length=6)
    name = models.CharField(max_length=100)

# The different Chapters in the book
class Chapter(models.Model):
    name = models.CharField(max_length=200)

# The different Lines of the chapters (by sections)
class Line(models.Model):
    chapter= models.ForeignKey(Chapter)
    section = models.IntegerField()
    line = models.IntegerField()

# The different translations of the line
class LineLanguage(models.Model):
    language = models.ForeignKey(Language)
    line = models.ForeignKey(Line)
    text = models.TextField()

然后我就有了美味的资源:

class LanguageResource(ModelResource):
    class Meta: queryset = Language.objects.all()
    resource_name = 'language'
    authorization = Authorization

class ChapterResource(ModelResource):
    class Meta: queryset = Chapter.objects.all()
    resource_name = 'chapter'
    authorization = Authorization()

class LineResource(ModelResource):
    chapter = fields.ForeignKey(ChapterResource, 'chapter')
    class Meta: queryset = Line.objects.all()
    resource_name = 'line'
    authorization = Authorization()

class LineLanguageResource(ModelResource):
    language= fields.ForeignKey(LanguageResource, 'language')
    line = fields.ForeignKey(LineResource, 'line')
    class Meta: queryset = LineLanguage.objects.all()
    resource_name = 'lineLanguage'
    authorization = Authorization()

最初我只想使用安静的服务(因此我的 url.py 只包含“ url(r'^api/', include(v1_api.urls)),”,但我无法得到我想要的:

我希望能够通过一个简单的调用来检索正确翻译中的特定文本行,但是如果不知道 LineLanguageID,这是不可能的。

在使用美味派之前。我的 url.py 中有一些设置允许我通过使用这种类型的 url 来找到它www.myapp.com/api/v1/language/chapter/section/line(例如,例如 www.myapp.com/api/v1/en/1/1/1会返回我英文第一章第一部分的第一行),但我想切换到 RESTFUL api(主要是因为我想尝试使用backbone.js)

我相信我的问题要么是我的模型/美味派资源设计不当,要么是缺乏如何将我的模型转换为适当的美味派资源的知识。你有什么建议?

4

1 回答 1

1

您可能会设计您的模型略有不同。我不知道您的其他需求是什么,但您可以将模型更改为如下所示:

#The different languages
class Language(models.Model):
    abbreviation = models.CharField(max_length=6)
    name = models.CharField(max_length=100)

# The different Lines of the chapters (by sections)
class Line(models.Model):
    name = models.CharField(max_length=200)
    section = models.IntegerField()
    line = models.IntegerField()
    language = models.ForeignKey(Language)
    text = models.TextField()

然后,您只需为Line模型定义一个资源,并使用类似于以下内容的请求查询语言/部分/章节/行:

www.myapp.com/api/v1/line/?language__abbreviation=en&section=1&chapter=1&line=1

如果你不想改变你的模型,你可以通过调用 api 来实现你想要的:

www.myapp.com/api/v1/lineLanguage/?language__abbreviation=en&line__line=1&line__section=1&line__chapter__name=1

请注意,对于这两种情况,资源的外键字段都需要full=True设置参数,因为您需要查询外部模型的字段。

如果您想使用旧的 url 模式,您可以通过override_urls在 LineLanguageResource 中定义包含处理来自 url 的参数的模式的方法来实现,将其传递给某个方法,然后将它们传递给美味的dispatch_detail方法作为 request.GET 元素。

于 2012-09-09T15:19:02.617 回答