1

When I have a related Resource, I would like to list foreign keys, instead of a url to that resource. How is that possible aside from dehydrating it?

4

1 回答 1

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')
于 2012-06-18T10:04:56.800 回答