当我有一个相关的资源时,我想列出外键,而不是该资源的URL。除了脱水之外怎么可能呢?
答案 0 :(得分:1)
我不确定没有脱水的可能性。我通常有实用函数来处理转换外键和多对多关系的脱水,如下所示:
#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')