我在Django项目中有类似的模型:
class Link(BaseModel, BeginEndModel):
entity0_content_type = models.ForeignKey(ContentType, related_name='link_from')
entity0_object_id = models.PositiveIntegerField()
entity0_content_object = generic.GenericForeignKey('entity0_content_type', 'entity0_object_id')
entity1_content_type = models.ForeignKey(ContentType, related_name='link_to')
entity1_object_id = models.PositiveIntegerField()
entity1_content_object = generic.GenericForeignKey('entity1_content_type', 'entity1_object_id')
link_type = models.ForeignKey(LinkType)
class Work(BaseModel, SluggedModel):
""" Eser """
name = models.CharField(max_length=255)
links = generic.GenericRelation('Link', content_type_field='entity0_content_type', object_id_field='entity0_object_id')
我想用Tasypie Api创建一个WorkResource:
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie import fields, utils
from tastypie.contrib.contenttypes.fields import GenericForeignKeyField
from tastypie.authentication import Authentication, SessionAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from models import Link, LinkType, LinkPhrase
from models import Work
....
class WorkResource( BaseModelResource ):
links = fields.ToManyField('musiclibrary.api.LinkResource', 'links_set')
class Meta:
queryset = Work.objects.all()
always_return_data = True
filtering = {
'slug': ALL,
'name': ['contains', 'exact']
}
class LinkResource( ModelResource ):
entity0_content_object = GenericForeignKeyField({
Work: WorkResource,
Artist: ArtistResource
}, 'entity0_content_object')
entity1_content_object = GenericForeignKeyField({
Work: WorkResource,
Artist: ArtistResource
}, 'entity1_content_object')
link_type = fields.ForeignKey(LinkTypeResource, 'link_type', full=True, null=True)
class Meta:
queryset = Link.objects.all()
当我想尝试查看工作资源结果时,links
属性始终为空数组。
为什么我无法建立2资源之间的关系?
注意:我使用Django 1.6.5,django-tastypie 0.11.1。我简化了上面的models.py和api.py示例。如果需要,我可以分享我的完整代码。
答案 0 :(得分:2)
它有点棘手,因为与ContentTypes飞来飞去的方式有两种关系。我想这会有所帮助:
class WorkResource( BaseModelResource ):
links = fields.ToManyField('musiclibrary.api.LinkResource', attribute=lambda bundle: Link.objects.filter(entity0_content_type=ContentType.objects.get_for_model(bundle.obj), entity0_object_id=bundle.obj.id))