无法在django-rest-framework中获取超链接字段

时间:2014-07-20 19:00:39

标签: django django-rest-framework

我的model.py交易和拆分中有两个模型。一个事务可以有很多分裂,我试图让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上here

1 个答案:

答案 0 :(得分:1)

您需要在split上将splits重命名为TransactionSerializer

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

如果没有重命名,目前序列化程序auto-generating splits字段为PrimaryKeyRelatedField。这就是为什么你将整数作为输出而不是你期望的链接。