更新: LocationResource 内の脱水は責任がありますか?
外部キーを介した逆引きが、配列自体ではなく、配列のネストされた文字列表現を返すという通常の状況があります。[I discovered this while using tastypie with backbone.js and backbone.marionette.][1]
奇妙なことに、fields.ForeignKey リソースから返されたネストされた配列がある場合でも、「前方」または通常のルックアップを実行すると、これは発生しません。
例えば:
前方参照:
[{"adult_price": "123", "child_price": "123", "currency": [{"abbrev": "USD", ... }] } ]
//--> notice that "currency" simply returns an array, without " "
逆引き - 外部キーによる「逆引き」
[{"id": "1", "name": "Venice", "resource_uri": "/api/v1/location/1/",
"theTours": "[{'subtitle': ... ... }]" } ]
//--> notice that there is a set of quotes " " outside the array for "theTours".
//--> a string representation of the array
以下は、リソース、およびモデルのセットアップです。
おいしいリソース
class LocationResource(ModelResource):
class Meta:
queryset = Location.objects.all()
resource_name = 'location'
def dehydrate(self, bundle):
bundle.data['theTours'] = Tours.objects.filter(location__name=bundle.obj.name).values()
return bundle
filtering = {
'name' : ALL_WITH_RELATIONS,
}
def override_urls(self):
return [
url(r"^(?i)(?P<resource_name>%s)/(?P<name>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
]
class CurrencyResource(ModelResource):
class Meta:
queryset = Currency.objects.all()
resource_name = 'currency'
filtering = {
'name' : ALL,
'abbrev' : ALL,
}
class ToursResource(ModelResource):
day = fields.ToManyField(DayOfWeekResource, 'day', full=True)
location = fields.ForeignKey(LocationResource, 'location', full=True, related_name="theLocs")
currency = fields.ToManyField(CurrencyResource, 'currency', full=True)
class Meta:
queryset = Tours.objects.all()
resource_name = 'tours'
limit = 100
filtering = {
'day' : ALL_WITH_RELATIONS,
'location' : ALL_WITH_RELATIONS,
'currency' : ALL_WITH_RELATIONS,
}
def override_urls(self):
return [
url(r"^(?i)(?P<resource_name>%s)/day/(?P<day__day_of_week>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
url(r"^(?i)(?P<resource_name>%s)/location/(?P<location__name>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_list'), name="api_dispatch_list"),
]
ジャンゴモデル
class Tours(models.Model):
location = models.ForeignKey('app.Location', related_name="theTours")
name = models.CharField(max_length=500)
currency = models.ManyToManyField('app.Currency')
class Meta:
verbose_name_plural = "Tours"
def __unicode__(self):
return self.name
class Location(models.Model):
name = models.CharField(max_length=50, unique=True)
def __unicode__(self):
return self.name
class Currency(models.Model):
abbrev = models.CharField(max_length=5, unique=True)
name = models.CharField(max_length=50, unique=True)
symbol = models.CharField(max_length=5)
class Meta:
verbose_name_plural = "Currencies"
def __unicode__(self):
return self.name