1
我有一個這樣的Django項目的一些型號:Django的Tastypie通用關係
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示例。如果需要,我可以分享我的完整代碼。