使用Django REST框架进行POST请求到一个带有嵌套序列化器的模型

huangapple go评论59阅读模式
英文:

POST request to a model with a nested serializer Django rest framework

问题

我有一个Product模型,它与Brand模型有多对一的关系

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,
    )
    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

Brand模型

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

唯一的方法是,如果我发送以下JSON,它不会引发axios错误,但当我这样做时,添加到数据库的产品的品牌设置为NULL

{
  "name": "examplename",
  "description": "example desc",
  "sku": "SKUSKUSKU",
  "asin": "ASINASIN12",
  "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);
        })
}

在向具有关系的模型发送数据时,我必须发送整个嵌套在JSON中的"brand"对象,还是只需发送"brand"的id(主键)?

我做错了什么?

编辑:
这是通过从Django管理页面手动创建的单个产品进行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"
    }
英文:

i have a Product model that has a many-to-one relationship with a Brand model

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

Brand model

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

    def __str__(self):
        return self.name

and a nested serializer

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

    class Meta:
        model = Product
        fields = "__all__"

when i make a POST request to add a new product to my table i keep getting errors and i cant figure out how to structure the json that is getting sent

the only way i can get it to not give an axios error is if i send the following JSON but when i do, the product that gets added to the database has the brand set as NULL

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

here is the function that sends the request

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);
        })
}

when posting data to a model that has a relationship, do i have to send the id (primary key) of the "brand" in this case or do i send the whole brand object nested in the JSON?

what am i doing wrong?

EDIT:
heres the correct JSON that i get when doing a GET request of a single product that was created manually from the django admin page

{
        "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"
    }

答案1

得分: 1

我认为你需要重写序列化器中的默认create()方法。

英文:

i think you have to override the default create() method in the serializer

huangapple
  • 本文由 发表于 2023年2月8日 23:04:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定