Reputation: 8411
I've two models in my model.py
Transaction and Split. A transaction can have many splits and I am trying to get django-rest-frameowrk to return response with hyper-linked relationship.
Something along the lines of this :
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"desc": "House Rent",
"currency": "INR",
"amount": 5000.0,
"splits": [
'http://www.example.com/api/splits/45/',
'http://www.example.com/api/splits/46/',
'http://www.example.com/api/splits/47/',
]
}
]
}
But no matter which field i try for the splits field in my TransactionSerializer I always get a response link this :
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"desc": "House Rent",
"currency": "INR",
"amount": 5000.0,
"splits": [
1,
2
]
}
]
}
The models and serializers that I've written are below Models :
class Transaction(models.Model):
desc = models.CharField(max_length=255)
currency = models.CharField(max_length=255)
amount = models.FloatField()
class Split(models.Model):
transaction = models.ForeignKey(Transaction, \
related_name='splits' )
userid = models.CharField(max_length=255)
split = models.IntegerField()
class Meta:
unique_together = ('transaction', 'userid')
Serializers :
class SplitSerializer(HyperlinkedModelSerializer):
class Meta:
model = Split
fields = ('transaction', 'userid', 'split')
class TransactionSerializer(serializers.ModelSerializer):
split = HyperlinkedRelatedField(many=True, \
view_name='split-detail')
class Meta:
model = Transaction
fields = ('desc', 'currency', 'amount', 'splits')
If you need the entire code of the project its available on github here
Upvotes: 0
Views: 130
Reputation: 41691
You need to rename split
to splits
on your TransactionSerializer
.
Right now, you have split
defined as the HyperlinkedRelatedField
you are looking for. You are not including split
in the fields
tuple within the serializer metadata, so it is not being included in the output. Once you rename it to splits
, it will be included in the output correctly and use the right relationship to generate the links.
Without the rename, currently the serializer is auto-generating the splits
field as a PrimaryKeyRelatedField
. This is why you are getting integers as the output instead of the links you were expecting.
Upvotes: 1