【问题标题】:Django Rest Framework Get Requests With Custom UrlDjango Rest Framework 使用自定义 URL 获取请求
【发布时间】:2016-12-20 11:40:33
【问题描述】:

我只是想向我的领域提出请求。但在这个获取请求中,我不想使用 pk。我只想使用条形码,您可以在下面看到模型。

我也是 Django 新手:

class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.CharField(max_length=255,null=True)
    barcode = models.BigIntegerField(unique=True, validators=[MaxValueValidator(13)])
    cover_photo = models.ImageField(upload_to='images/', blank=True, null=True)
    description = models.CharField(max_length=255,null=True)
    product_url = models.CharField(max_length=255,null=True)
    product_company = models.ForeignKey(Company, blank=True, null=True)

    fields = ['barcode', 'name', 'cover_photo', 'product_url', 'price']
    def __unicode__(self):
        return self.name.encode('utf-8')

这也是我的网址。

 url(r'^api/products/(?P<barcode>)/$',product_detail, name="product_detail"),
product_detail = views.ProductViewSet.as_view({
    'get': 'retrieve'
})

这是我的观点。

class ProductViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

【问题讨论】:

    标签: python django django-models django-views django-rest-framework


    【解决方案1】:

    尝试在您的ProductViewSet 中设置lookup_field = 'barcode',即

    class ProductViewSet(viewsets.ReadOnlyModelViewSet):
        queryset = Product.objects.all()
        serializer_class = ProductSerializer
        lookup_field = 'barcode'
    

    并在 urls 中设置正则表达式模式(注意[0-9]{1,13},它将匹配长度在 1 到 13 之间的任何数字):

    url(r'^api/products/(?P<barcode>[0-9]{1,13})/$',product_detail, name="product_detail")
    

    also checkout code for class GenericAPIView

    【讨论】:

    • 我试过你说的但现在它返回 404。没有改变任何东西
    • @MuratKaya 保留您所保留的 url 并尝试在视图中设置查找字段 = 'barcode'。
    • @MuratKaya 你能在这两种情况下都发送 response.data 吗?
    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 2016-12-29
    • 2020-12-07
    • 2018-03-17
    • 1970-01-01
    • 2012-05-26
    • 2021-05-31
    • 2017-10-16
    相关资源
    最近更新 更多