无法在django rest框架中获取超链接字段

无法在django rest框架中获取超链接字段,django,django-rest-framework,Django,Django Rest Framework,我的model.pyTransaction和Split中有两个模型。一个事务可以有许多拆分,我正试图让django rest frameowrk返回具有超链接关系的响应 大致如下: { "count": 1, "next": null, "previous": null, "results": [ { "desc": "House Rent", "currency": "INR",

我的
model.py
Transaction和Split中有两个模型。一个事务可以有许多拆分,我正试图让django rest frameowrk返回具有超链接关系的响应

大致如下:

{
    "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/',
            ]
        }
    ]
}
但无论我在TransactionSerializer中尝试使用哪个字段的拆分字段,我都会得到以下响应链接:

{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "desc": "House Rent", 
            "currency": "INR", 
            "amount": 5000.0, 
            "splits": [
                1, 
                2
            ]
        }
    ]
}
下面是我编写的模型和序列化程序 型号:

  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')
序列化程序:

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')    

如果您需要项目的整个代码,它可以在github上获得

您需要在
TransactionSerializer上将
拆分
重命名为
拆分

现在,您已经将
split
定义为您要查找的
HyperlinkedRelatedField
。序列化程序元数据中的
字段
元组中没有包含
split
,因此输出中没有包含它。一旦您将其重命名为
splits
,它将正确地包含在输出中,并使用正确的关系生成链接


如果没有重命名,当前序列化程序是将
字段拆分为
PrimaryKeyRelatedField
。这就是为什么您将整数作为输出,而不是预期的链接。

工作得很好,非常感谢您的快速帮助:)