簡體   English   中英

DjangoFilterBackend:過濾主鍵會導致“選擇一個有效的選擇。該選擇不是可用的選擇之一。”

[英]DjangoFilterBackend: Filtering on a primary key results in "Select a valid choice. That choice is not one of the available choices."

我有兩個模型(產品和類別),每個產品都有一個鏈接的類別。

我已經安裝了DjangoFilterBackend ,希望在category字段上進行過濾以返回該類別中的產品列表。

但是,每當我在 Postman 中發送查詢時。 我收到錯誤Select a valid choice. That choice is not one of the available choices. Select a valid choice. That choice is not one of the available choices. .

我嘗試在我的product model (示例name )中過濾另一個字段,效果很好。 所以我不確定我是否遺漏了一些讓category起作用的東西。

Product/View.py

class ProductView(ListAPIView):
    serializer_class = ProductSerializer
    queryset = Product.objects.all()
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ('category', 'name')

Products/Models.py

class Product(models.Model):
    name = models.CharField(max_length=250, unique=True, blank=False)
    photo = models.ImageField(upload_to=product_photo_path)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    description = models.TextField(blank=False)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    in_stock = models.BooleanField(default=False)
    trending = models.BooleanField(default=False)

    def __str__(self):
        return self.name

Products/serializers.py

class ProductSerializer(serializers.ModelSerializer):
    category = serializers.CharField(source='category.name', read_only=True)

    class Meta:
        model = Product
        fields = ('category', 'name', 'photo', 'quantity', 'description', 'price', 'in_stock', 'trending')

我正在使用的查詢是一個 GET 請求:

http://127.0.0.1:8000/api/products?category=xxxx - I am sending no payload. The response I am receiving is a `400 Bad Request` and the exact error is:

{
    "category": [
        "Select a valid choice. That choice is not one of the available choices."
    ]
}

啊哈!

我將 model 更改為:

class Product(models.Model):
    name = models.CharField(max_length=250, unique=True, blank=False)
    photo = models.ImageField(upload_to=product_photo_path)
    **category = models.ForeignKey(Category, to_field='name', on_delete=models.CASCADE)**
    quantity = models.IntegerField()
    description = models.TextField(blank=False)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    in_stock = models.BooleanField(default=False)
    trending = models.BooleanField(default=False)

現在它起作用了!

好吧,我不確定,但嘗試過濾字段category_id ,該字段是為 FK 字段自動創建的

以防萬一有人需要答案,為了能夠使用外部字段的名稱而不是主鍵進行過濾,請使用雙下划線,即在這種情況下category__name 請注意,在這種情況下,名稱是您要過濾的外部 model 的字段,您可以相應地將其替換為您的字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM