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

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

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

问题

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

  1. class Product(models.Model):
  2. name = models.CharField(max_length=200)
  3. description = models.CharField(max_length=500)
  4. sku = models.CharField(max_length=50)
  5. upc = models.CharField(max_length=12, blank=True)
  6. asin = models.CharField(max_length=10, blank=True)
  7. brand = models.ForeignKey(
  8. Brand,
  9. on_delete=models.CASCADE,
  10. null=True,
  11. )
  12. vendors = models.ManyToManyField(Vendor, blank=True)
  13. added = models.DateTimeField(auto_now_add=True)
  14. updated = models.DateTimeField(auto_now=True)
  15. def __str__(self):
  16. return self.name + ":" + self.description

Brand模型

  1. class Brand(models.Model):
  2. name = models.CharField(max_length=50)
  3. def __str__(self):
  4. return self.name

以及嵌套的序列化器

  1. class ProductSerializer(serializers.ModelSerializer):
  2. brand = BrandSerializer(required=False, read_only=True)
  3. class Meta:
  4. model = Product
  5. fields = "__all__"

当我发出POST请求以将新产品添加到我的表时,我一直收到错误,而我无法弄清楚如何构造发送的JSON

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

  1. {
  2. "name": "examplename",
  3. "description": "example desc",
  4. "sku": "SKUSKUSKU",
  5. "asin": "ASINASIN12",
  6. "brand": {
  7. "id": 1,
  8. "name": "Honeywell"
  9. }
  10. }

这是发送请求的函数

  1. function addProduct(product) {
  2. // axios post request for a new product
  3. console.log(product)
  4. axios.post("http://127.0.0.1:8000/products/", product)
  5. .then((response) => {
  6. console.log(response);
  7. alert("Success");
  8. reset('productForm')
  9. })
  10. .catch((error) => {
  11. console.log(error);
  12. alert(error);
  13. })
  14. }

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

我做错了什么?

编辑:
这是通过从Django管理页面手动创建的单个产品进行GET请求时获取的正确JSON

  1. {
  2. "id": 9,
  3. "brand": {
  4. "id": 2,
  5. "name": "Beano"
  6. },
  7. "vendors": [],
  8. "name": "beans",
  9. "description": "big ol can o beans",
  10. "sku": "beansbeansbeans",
  11. "upc": "",
  12. "asin": "bB00nvn",
  13. "added": "2022-12-28T19:09:30.007480Z",
  14. "updated": "2022-12-28T19:09:30.013781Z"
  15. }
英文:

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

  1. class Product(models.Model):
  2. name = models.CharField(max_length=200)
  3. description = models.CharField(max_length=500)
  4. sku = models.CharField(max_length=50)
  5. upc = models.CharField(max_length=12, blank=True)
  6. asin = models.CharField(max_length=10, blank=True)
  7. brand = models.ForeignKey(
  8. Brand,
  9. on_delete=models.CASCADE,
  10. null=True,
  11. )
  12. # buybox = models.FloatField(blank=True)
  13. vendors = models.ManyToManyField(Vendor, blank=True)
  14. added = models.DateTimeField(auto_now_add=True)
  15. updated = models.DateTimeField(auto_now=True)
  16. def __str__(self):
  17. return self.name + ": " + self.description

Brand model

  1. class Brand(models.Model):
  2. name = models.CharField(max_length=50)
  3. def __str__(self):
  4. return self.name

and a nested serializer

  1. class ProductSerializer(serializers.ModelSerializer):
  2. brand = BrandSerializer(required=False, read_only=True)
  3. class Meta:
  4. model = Product
  5. 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

  1. {
  2. "name": "examplename",
  3. "description": "example desc",
  4. "sku": "SKUSKUSKU",
  5. "asin": "ASINASIN12",
  6. "price": "11.11",
  7. "brand": {
  8. "id": 1,
  9. "name": "Honeywell"
  10. }
  11. }

here is the function that sends the request

  1. function addProduct(product) {
  2. // axios post request for a new product
  3. console.log(product)
  4. axios.post("http://127.0.0.1:8000/products/", product)
  5. .then((response) => {
  6. console.log(response);
  7. alert("Success");
  8. reset('productForm')
  9. })
  10. .catch((error) => {
  11. console.log(error);
  12. alert(error);
  13. })
  14. }

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

  1. {
  2. "id": 9,
  3. "brand": {
  4. "id": 2,
  5. "name": "Beano"
  6. },
  7. "vendors": [],
  8. "name": "beans",
  9. "description": "big ol can o beans",
  10. "sku": "beansbeansbeans",
  11. "upc": "",
  12. "asin": "bB00nvn",
  13. "added": "2022-12-28T19:09:30.007480Z",
  14. "updated": "2022-12-28T19:09:30.013781Z"
  15. }

答案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:

确定