【问题标题】:Django (Rest Framework): create (POST) a nested/sub-resource using hyperlinked relationsDjango(Rest Framework):使用超链接关系创建(POST)嵌套/子资源
【发布时间】: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


【解决方案1】:

好吧,我对rest_framework 进行了一些研究,似乎不匹配是由于 URL 模式匹配没有解析到您的适当视图命名空间。在here 周围做一些打印,您会看到expected_viewnameself.view_name 不匹配。

检查您的应用程序上的视图命名空间是否正确(这些视图似乎位于命名空间customer-resource 下),如果需要,通过序列化程序上的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'}

希望这对你有用;)

【讨论】:

    【解决方案2】:

    我不确定是否理解得很好,但是如果您说 customer_id 是主键,我认为如果您在 CustomerContactSerializer 中指定 customer 是 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')
    

    【讨论】:

      【解决方案3】:

      网址末尾必须包含/

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

      这应该可行。

      【讨论】:

      • 尾随斜杠没有解决我的情况。你测试成功了吗?
      • 我回答了这个问题〜一年前,所以我现在不记得了 :) 正如我现在看到的问题在cust_contact_data['customer'] = cust_id 行。默认情况下,超链接序列化程序期望将客户 URL 作为客户,而不是 id。
      猜你喜欢
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 2016-12-28
      • 2016-01-20
      • 1970-01-01
      • 2014-12-15
      • 2017-10-19
      • 1970-01-01
      相关资源
      最近更新 更多