【问题标题】:Django REST framework - HyperlinkedRelatedField with additional parameterDjango REST 框架 - 带有附加参数的 HyperlinkedRelatedField
【发布时间】:2015-07-30 08:09:18
【问题描述】:

我正在使用 Django Rest 框架构建 REST Web API。 我在类别和钱包之间有多对多的关系。 从一个类别开始,我检索其链接到的所有钱包,并且从 shell 中一切正常

型号:

class Wallet(models.Model):
    nome = models.CharField(max_length=255)
    creato = models.DateTimeField(auto_now=False)
    utente = models.ForeignKey(User)
    wallettype = models.ForeignKey(Wallettype)
    payway = models.ManyToManyField(Payway, through = 'Wpw', blank = True)
    defaultpayway = models.ForeignKey('Wpw', related_name = 'def_pw', null = True)

    def __unicode__(self):
        return self.nome

class Category(models.Model):
    nome = models.CharField(max_length=255)
    creato = models.DateTimeField(auto_now=False)
    enus = models.ForeignKey(Enus)
    wallet = models.ManyToManyField(Wallet)
    utente = models.ForeignKey(User)
    owner = models.ManyToManyField(User, related_name='owner_cat')

网址:

urlpatterns = patterns(
    '',
    url(r'^$', views.cat_list.as_view()),
    url(r'^/(?P<pk>[0-9]+)/*$', views.cat_detail.as_view()),
    url(r'^/(?P<cat_id>[0-9]+)/wallets/*$', views.cwallet_list.as_view()),
    url(r'^/(?P<cat_id>[0-9]+)/wallets/(?P<pk>[0-9]+)/*$', views.cwallet_detail.as_view(), name='cwallet-detail'),
)

序列化器:

class cat_serializer(serializers.ModelSerializer):
    wallet = serializers.HyperlinkedRelatedField(
        many=True,
        read_only=True,
        view_name='cwallet-detail',
        # lookup_field = 'pk',
        # lookup_url_kwarg = 'pk'
    )
    subcat_count = serializers.IntegerField(
        source='subcategory_set.count',
        read_only=True
    )

    class Meta:
        model = Category
        fields = ('id', 'nome','wallet','subcat_count')

当我打电话时:

GET http://localhost:8000/categories/77/wallets

我想找回:

{
    'nome': 'Dinner',
    'subcat_count': 12,
    'wallet': {
        'http://localhost:8000/77/wallet/1',
        'http://localhost:8000/77/wallet/2',
        'http://localhost:8000/77/wallet/3',
    }
}

但它不起作用,我收到此错误:
“无法使用视图名称“cwallet-detail”解析超链接关系的 URL。您可能未能在 API 中包含相关模型, 或在该字段上错误地配置了lookup_field 属性。”

我认为问题与附加参数有关:事实上,在我的 urls.py 中,钱包 ID 为 pk,类别 ID 为 cat_id。 我不知道如何将类别 ID 传递给“cwallet-detail”。

有人知道如何将第二个参数传递给 HyperlinkedRelatedField 吗?
提前谢谢你。

【问题讨论】:

    标签: python django rest


    【解决方案1】:

    阅读文档并在Tom Christie's Django REST github 上发布new issue 后,现在我知道它不受官方支持,但文档和补丁正在进行中。

    其实有 this link 用于构建自定义超链接文件来解决问题。

    希望这对有同样问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-25
      • 2019-05-01
      • 2015-05-10
      • 2023-03-17
      • 2018-08-06
      • 2016-06-25
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多