axios 使用嵌套的序列化器Django rest框架对模型的POST请求

r7knjye2  于 2023-02-12  发布在  iOS
关注(0)|答案(1)|浏览(128)

我有一个与品牌型号具有多对一关系的产品型号

class Product(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=500)
    sku = models.CharField(max_length=50)
    upc = models.CharField(max_length=12, blank=True)
    asin = models.CharField(max_length=10, blank=True)
    brand = models.ForeignKey(
        Brand,
        on_delete=models.CASCADE,
        null=True,
    )
    # buybox = models.FloatField(blank=True)
    vendors = models.ManyToManyField(Vendor, blank=True)
    added = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name + ": " + self.description

品牌模式

class Brand(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

和嵌套的串行化程序

class ProductSerializer(serializers.ModelSerializer):
    brand = BrandSerializer(required=False, read_only=True)

    class Meta:
        model = Product
        fields = "__all__"

当我发出POST请求向表中添加新产品时,我不断收到错误,并且我无法弄清楚如何构造要发送的JSON
我可以让它不给出axios错误的唯一方法是发送以下JSON,但是当我这样做时,添加到数据库中的产品的品牌设置为NULL

{
  "name": "examplename",
  "description": "example desc",
  "sku": "SKUSKUSKU",
  "asin": "ASINASIN12",
  "price": "11.11",
  "brand": {
    "id": 1,
    "name": "Honeywell"
  }
}

下面是发送请求的函数

function addProduct(product) {
    // axios post request for a new product
    console.log(product)
    axios.post("http://127.0.0.1:8000/products/", product)
        .then((response) => {
            console.log(response);
            alert("Success");
            reset('productForm')

        })
        .catch((error) => {
            console.log(error);
            alert(error);
        })
}

当向一个有关系的模型发布数据时,我是必须发送"brand"的id(主键),还是发送嵌套在JSON中的整个brand对象?
我做错了什么?
编辑:这是我在djangoadmin页面手动创建的单个产品的GET请求时得到的正确JSON

{
        "id": 9,
        "brand": {
            "id": 2,
            "name": "Beano"
        },
        "vendors": [],
        "name": "beans",
        "description": "big ol can o beans",
        "sku": "beansbeansbeans",
        "upc": "",
        "asin": "bB00nvn",
        "added": "2022-12-28T19:09:30.007480Z",
        "updated": "2022-12-28T19:09:30.013781Z"
    }
ncecgwcz

ncecgwcz1#

我认为您必须覆盖序列化程序中的默认create()方法

相关问题