Django Rest框架使用自定义U获取请求

2024-04-26 11:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是想用我的领域提出get请求。但是在这个get请求中我不想使用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')

这也是我的网址。在

^{pr2}$

这是我的观点。在

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

Tags: nametruegetmodelscoverproductnulllength
1条回答
网友
1楼 · 发布于 2024-04-26 11:36:06

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

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

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

^{pr2}$

also checkout code for class GenericAPIView

相关问题 更多 >