Reputation: 26477
I'm doing my best to return values of related record ids (foreign key reference) using tastypie. By default, foreign keys are filtered out from the result.
I've got a following model:
class Category(models.Model):
"""Finance category"""
class Meta:
db_table = 'category'
parent = models.ForeignKey('self')
name = models.CharField(max_length=32)
TYPES = (
('outcome', 'outcome'),
('income', 'income'),
)
type = models.CharField(max_length=7,choices=TYPES)
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
created_by = models.ForeignKey(User, db_column='created_by', related_name='createdCategories')
updated_by = models.ForeignKey(User, db_column='updated_by', related_name='updatedCategories')
I've got two relations here. parent
is recursive relation (it's a category tree table). created_by
is a relation to the user. API is returning following values:
* id
* name
* created_at
* updated_at
* type
* resource_uri
What can I do to make tastypie return parent(_id) or created_by (or just any foreign key)?
The following is what I've tried from another OS question:
class IncomeCategoryResource(ModelResource):
parent_id = models.IntegerField(attribute="parent_id")
class Meta:
queryset = Category.objects.filter(type='income')
Unfortunately, the whole API fails:
__init__() got an unexpected keyword argument 'attribute'
I've also tried to replace attribute
kwarg with db_column
. This one is just ignored.
Help me, please :)
Upvotes: 2
Views: 1606
Reputation: 2609
First off, the IntegerField
there is wrong. You should be using tastypie's fields (tastypie.fields), not django model fields (django.db.models). Then your resource should look like:
class IncomeCategoryResource(ModelResource):
parent_id = IntegerField(attribute="parent__id")
class Meta:
queryset = Category.objects.filter(type='income')
Note the use of double underscore to get to the parent's id field.
Upvotes: 4