Reputation: 7032
I have two legacy models listed below. The Library.libtype_id
is effectively a foreign key to LibraryType when libtype_id > 0. I want to represent this as a ForeignKey Resource in TastyPie when that condition is met.
Can someone help me out? I have seen this but I'm not sure it's the same thing? Thanks much!!
# models.py
class LibraryType(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=96)
class Library(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
project = models.ForeignKey('project.Project', db_column='parent')
libtype_id = models.IntegerField(db_column='libTypeId')
Here is my api.py
class LibraryTypeResource(ModelResource):
class Meta:
queryset = LibraryType.objects.all()
resource_name = 'library_type'
class LibraryResource(ModelResource):
project = fields.ForeignKey(ProjectResource, 'project')
libtype = fields.ForeignKey(LibraryTypeResource, 'libtype_id' )
class Meta:
queryset = Library.objects.all()
resource_name = 'library'
exclude = ['libtype_id']
def dehydrate_libtype(self, bundle):
if getattr(bundle.obj, 'libtype_id', None) != 0:
return LibraryTypeResource.get_detail(id=bundle.obj.libtype_id)
When I do this however I'm getting the following error on http://0.0.0.0:8001/api/v1/library/?format=json
"error_message": "'long' object has no attribute 'pk'",
Upvotes: 0
Views: 1070
Reputation: 9346
Shouldn't
libtype = fields.ForeignKey(LibraryTypeResource, 'libtype_id' )
be
libtype = fields.ForeignKey(LibraryTypeResource, 'libtype' )
(without the '_id')
I believe that as it is you are handing the field an int
and it is attempting to get the pk
from it.
UPDATE:
Missed that libtype_id
is an IntegerField
, not a ForeignKey
(whole point of the question)
Personally I would add a method to the Library
to retrieve the LibraryType
object. This way you have access to the LibraryType
from the Library
and you don't have to override any dehydrate
methods.
class Library(models.Model):
# ... other fields
libtype_id = models.IntegerField(db_column='libTypeId')
def get_libtype(self):
return LibraryType.objects.get(id=self.libtype_id)
.
class LibraryResource(ModelResource):
libtype = fields.ForeignKey(LibraryTypeResource, 'get_libtype')
Upvotes: 1