【发布时间】:2015-09-18 11:20:42
【问题描述】:
我很难理解超链接序列化程序是如何工作的。如果我使用普通模型序列化程序,一切正常(返回 id 等)。但我更愿意返回 url,这更像是 RESTful imo。
我正在使用的示例看起来非常简单和标准。 我有一个 API,它允许“管理员”在系统上创建客户(在本例中为公司)。客户具有属性“name”、“accountNumber”和“billingAddress”。这存储在数据库的 Customer 表中。 “管理员”还可以创建客户联系人(客户/公司的个人/联系人)。
创建客户的 API 是 /customer。当针对此执行 POST 并成功时,将在 /customer/{cust_id} 下创建新的 Customer 资源。
随后,用于创建客户联系人的 API 为 /customer/{cust_id}/contact。当针对此执行 POST 并成功时,将在 /customer/{cust_id}/contact/{contact_id} 下创建新的客户联系人资源。
我认为这很简单,是面向资源架构的一个很好的例子。
这是我的模型:
class Customer(models.Model):
name = models.CharField(max_length=50)
account_number = models.CharField(max_length=30, name="account_number")
billing_address = models.CharField(max_length=100, name="billing_address")
class CustomerContact(models.Model):
first_name = models.CharField(max_length=50, name="first_name")
last_name = models.CharField(max_length=50, name="last_name")
email = models.CharField(max_length=30)
customer = models.ForeignKey(Customer, related_name="customer")
所以在 CustomerContact 和 Customer 之间存在 外键(多对一)关系。
创建客户非常简单:
class CustomerViewSet(viewsets.ViewSet):
# /customer POST
def create(self, request):
cust_serializer = CustomerSerializer(data=request.data, context={'request': request})
if cust_serializer.is_valid():
cust_serializer.save()
headers = dict()
headers['Location'] = cust_serializer.data['url']
return Response(cust_serializer.data, headers=headers, status=HTTP_201_CREATED)
return Response(cust_serializer.errors, status=HTTP_400_BAD_REQUEST)
创建 CustomerContact 有点棘手,因为我必须获取客户的外键,将其添加到请求数据并将其传递给序列化程序(我不确定这是否是正确/最佳的方法它)。
class CustomerContactViewSet(viewsets.ViewSet):
# /customer/{cust_id}/contact POST
def create(self, request, cust_id=None):
cust_contact_data = dict(request.data)
cust_contact_data['customer'] = cust_id
cust_contact_serializer = CustomerContactSerializer(data=cust_contact_data, context={'request': request})
if cust_contact_serializer.is_valid():
cust_contact_serializer.save()
headers = dict()
cust_contact_id = cust_contact_serializer.data['id']
headers['Location'] = reverse("customer-resource:customercontact-detail", args=[cust_id, cust_contact_id], request=request)
return Response(cust_contact_serializer.data, headers=headers, status=HTTP_201_CREATED)
return Response(cust_contact_serializer.errors, status=HTTP_400_BAD_REQUEST)
客户的序列化程序是
class CustomerSerializer(serializers.HyperlinkedModelSerializer):
accountNumber = serializers.CharField(source='account_number', required=True)
billingAddress = serializers.CharField(source='billing_address', required=True)
customerContact = serializers.SerializerMethodField(method_name='get_contact_url')
url = serializers.HyperlinkedIdentityField(view_name='customer-resource:customer-detail')
class Meta:
model = Customer
fields = ('url', 'name', 'accountNumber', 'billingAddress', 'customerContact')
def get_contact_url(self, obj):
return reverse("customer-resource:customercontact-list", args=[obj.id], request=self.context.get('request'))
注意(并且可能忽略)customerContact SerializerMethodField(我在 Customer 资源的表示中返回 CustomerContact 的 URL)。
CustomerContact 的序列化程序是:
class CustomerContactSerializer(serializers.HyperlinkedModelSerializer):
firstName = serializers.CharField(source='first_name', required=True)
lastName = serializers.CharField(source='last_name', required=True)
url = serializers.HyperlinkedIdentityField(view_name='customer-resource:customercontact-detail')
class Meta:
model = CustomerContact
fields = ('url', 'firstName', 'lastName', 'email', 'customer')
'customer' 是对 CustomerContact 模型/表中客户外键的引用。所以当我做这样的POST时:
POST http://localhost:8000/customer/5/contact
body: {"firstName": "a", "lastName":"b", "email":"a@b.com"}
我回来了:
{
"customer": [
"Invalid hyperlink - No URL match."
]
}
所以看起来外键关系必须在 HyperlinkedModelSerializer 中表示为 URL? DRF 教程 (http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/#hyperlinking-our-api) 似乎也这么说:
Relationships use HyperlinkedRelatedField, instead of PrimaryKeyRelatedField
我可能在我的 CustomerContactViewSet 中做错了什么,是否在将 customer_id 添加到请求数据之前将其传递给序列化程序 (cust_contact_data['customer'] = cust_id) 不正确?
我尝试将 URL 传递给它 - http://localhost:8000/customer/5 - 从上面的 POST 示例中,但我得到一个稍微不同的错误:
{
"customer": [
"Invalid hyperlink - Incorrect URL match."
]
}
如何使用 HyperlinkedModelSerializer 创建与另一个模型具有外键关系的实体?
【问题讨论】:
-
嗨@Cliff Sun 我遇到了一个非常相似的问题,你有没有设法解决这个问题?
-
嘿@Cliff Sun 我设法为我解决了这个问题,请在下面查看我的答案;)
标签: python django rest django-rest-framework hateoas