I have some models like that in a Django project:
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')
I want to create a WorkResource with Tasypie Api like that:
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()
When I want to try to see work resource result, links
attribute is always an empty array.
Why I couldn't make a relation between 2 resource?
Note: I use Django 1.6.5, django-tastypie 0.11.1. I simplified my models.py and api.py samples above. If needed I can share my full codes.
Its a bit tricky since there is 2 way relationship with ContentTypes flying around. I guess this would help :
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))