1
當我有相關資源時,我想列出外鍵,而不是該資源的網址。除了脫水之外,這可能如何?tastypie - 列出相關資源密鑰而不是網址
當我有相關資源時,我想列出外鍵,而不是該資源的網址。除了脫水之外,這可能如何?tastypie - 列出相關資源密鑰而不是網址
我不確定沒有脫水現場就可能。我通常有處理轉換外鍵和many-to-many關係,有事的脫水這樣的實用功能:
#api_utils.py
def many_to_many_to_ids(bundle, field_name):
field_ids = getattr(bundle.obj, field_name).values_list('id', flat=True)
field_ids = map(int, field_ids)
return field_ids
def foreign_key_to_id(bundle, field_name):
field = getattr(bundle.obj, field_name)
field_id = getattr(field, 'id', None)
return field_id
並將其應用到像這樣的字段:
#api.py
from functools import partial
class CompanyResource(CommonModelResource):
categories = fields.ManyToManyField(CompanyCategoryResource, 'categories')
class Meta(CommonModelResource.Meta):
queryset = Company.objects.all()
dehydrate_categories = partial(many_to_many_to_ids, field_name='categories')
class HotDealResource(CommonModelResource):
company = fields.ForeignKey(CompanyResource, 'company')
class Meta(CommonModelResource.Meta):
queryset = HotDeal.objects.all()
dehydrate_company = partial(foreign_key_to_id, field_name='company')