【发布时间】: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 吗?
提前谢谢你。
【问题讨论】: