【问题标题】:How to use django-multiselect field in postman?如何在邮递员中使用 django-multiselect 字段?
【发布时间】:2020-09-14 21:46:50
【问题描述】:

我正在使用 pip 模块 MultiSelectField 这是我的模型

SALES_CHANNEL = [
    ('retailer', 'Retailer'),
    ('wholesaler', 'Wholesaler'),
    ('consumer', 'Consumer'),
    ('distributor', 'Distributor'),
    ('online', 'Online')
]

class ProductModel(basemodel.BaseModel):
    name = models.CharField(max_length=200)
    mrp = models.DecimalField(
        max_digits=10, decimal_places=2,
        null=True, blank=True
    )
    selling_price = models.DecimalField(
        max_digits=10, decimal_places=2,
        null=True, blank=True
    )
    upc = models.CharField(max_length=30, null=True, blank=True)
    dimensions = models.CharField(max_length=200, null=True, blank=True)
    weight = models.CharField(max_length=200, null=True, blank=True)
    sku = models.CharField(max_length=200, unique=True)
    product_type = models.CharField(
        max_length=30, choices=PRODUCT_TYPE, default='goods'
    )
    sales_channel = MultiSelectField(
        choices=SALES_CHANNEL, null=True, blank=True
    )

在使用邮递员创建产品时,我的请求正文是:

{
    "name": "first unit",
    "sku": "first sales chann",
    "sales_channel":["retailer", "wholesaler"]

}

但是在 serializer.is_valid() 上,我得到了这个错误:

        "sales_channel": [
            "\"['retailer', 'wholesaler']\" is not a valid choice."
        ],

如何在 postman 上为多选字段发布数据?

【问题讨论】:

    标签: django django-models django-rest-framework postman django-multiselectfield


    【解决方案1】:

    对@skhynixsk 当前接受的答案的小更新 我发现使用MultipleChoiceField() 而不是ListField() 更好,因为我们可以在MultipleChoiceField() 中传递正确的选择进行验证。如果我们只使用ListField(),它将接受任何正确的选择,而不是验证所需的正确选择。

    sales_channel = serializers.MultipleChoiceField(["retailer", "wholesaler"])

    更多关于MultipleChoiceField()here

    【讨论】:

      【解决方案2】:

      您可以在表单数据中多次发布 sales_channel,例如:

      sales_channel:零售商 sales_cahnnel:批发商

      N.B:不在原始数据中。 好吧好吧,我来帮你。您能否在元数据前将以下详细信息添加到您的序列化程序中:

      class YourSerializer(serializers.ModelSerializer):
      sales_channel = serializers.ListField()
           class Meta:
               model = YourModel
      

      【讨论】:

      • 但是如何在 raw_data 中实现这一点?我仅将我的所有数据作为 raw_data 发送,无法更改
      【解决方案3】:

      为了实现这一点,您需要更改序列化程序

      from rest_framework import fields    
      
      class CustomMultipleChoiceField(fields.MultipleChoiceField):
          def to_representation(self, value):
              return list(super().to_representation(value))
      
      class YourSerializer(serializers.ModelSerializer):
          sales_channel = CustomMultipleChoiceField(choices=SALES_CHANNEL, required=False)
      
          class Meta:
              model = ProductModel
              fields = '__all__'
      

      【讨论】:

        猜你喜欢
        • 2017-11-03
        • 2018-01-01
        • 2017-08-15
        • 1970-01-01
        • 2017-06-17
        • 1970-01-01
        • 2021-04-09
        • 2018-08-29
        • 2021-07-24
        相关资源
        最近更新 更多