Django(Rest Framework):使用超链接关系创建(POST)嵌套/子资源



我很难理解超链接序列化程序是如何工作的。如果我使用普通的模型序列化程序,一切都很好(返回id等(。但我更愿意返回url,这是一个更RESTful的imo。

我正在使用的示例看起来非常简单和标准。我有一个API,它允许"管理员"在系统上创建一个客户(在这种情况下是一家公司(。客户具有"name"、"accountNumber"one_answers"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有点棘手,因为我必须获取Customer的外键,将其添加到请求数据中,并将其传递给序列化程序(我不确定这是否是正确/最佳的方法(。

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 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-我们的api(似乎也这么说:

Relationships use HyperlinkedRelatedField, instead of PrimaryKeyRelatedField

我可能在我的CustomerContactViewSet中做了一些错误的事情,在将customer_id传递给序列化程序(cust_contact_data['customer'] = cust_id(之前将其添加到请求数据中是否不正确?我试着从上面的POST示例中向它传递一个URL http://localhost:8000/customer/5,但我得到了一个稍微不同的错误:

{
    "customer": [
        "Invalid hyperlink - Incorrect URL match."
    ]
}

如何使用HyperlinkedModelSerializer创建与另一个模型具有外键关系的实体?

好吧,我深入研究了rest_framework,似乎不匹配是由于URL模式匹配没有解析到合适的视图命名空间。在这里打印一下,你可以看到expected_viewnameself.view_name不匹配。

检查您的应用程序上的视图名称空间是否正确(这些视图似乎在名称空间customer-resource下(,如果需要,请通过Serializer Meta:上的extra_kwargs修复相关超链接相关字段上的view_name属性

class CustomerContactSerializer(serializers.HyperlinkedModelSerializer):
    firstName = serializers.CharField(source='first_name', required=True)
    lastName = serializers.CharField(source='last_name', required=True)
    url = serializers.HyperlinkedIdentityField()
    class Meta:
        model = CustomerContact
        fields = ('url', 'firstName', 'lastName', 'email', 'customer')
        extra_kwargs = {'view_name': 'customer-resource:customer-detail'}

希望这对你有用;(

我不一定能很好地理解,但如果customer_id像你说的那样是主键,我认为如果你在CustomerContactSerializer中指定客户是PrimaryKeyRelatedField,你就可以解决你的问题,比如。

class CustomerContactSerializer(serializers.HyperlinkedModelSerializer):
    firstName = serializers.CharField(source='first_name', required=True)
    lastName = serializers.CharField(source='last_name', required=True)
    customer = serializers.PrimaryKeyRelatedField(
            queryset=Customer.objects.all(),
            many=False)
    class Meta:
        model = CustomerContact
        fields = ('url', 'firstName', 'lastName', 'email', 'customer')

URL必须在末尾包含/

cust_contact_data['customer'] = 'http://localhost:8000/customer/5/'

这应该行得通。