首页 > 解决方案 > (1048,“列'brand_id'不能为空”)在django rest框架中

问题描述

我正在尝试创建一个 api,用户可以在其中添加他们的产品。我正在从邮递员发送原始 json 数据,但它给出了这个错误。

/api/addproducts 处的 IntegrityError(1048,“列 'brand_id' 不能为空”)

我在数据中发送品牌 ID。我不确定发生了什么。

在此处输入图像描述

在这里,我发送了 Mercer_id 以及类别 ID,但我不确定为什么品牌字段会产生错误。

我的模型:

class Category(models.Model):
    name = models.CharField(max_length=100, unique=True)
    image = models.ImageField(null=True, blank=True)


    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.name

    class Brand(models.Model):
    brand_category = models.ForeignKey(Category,on_delete=models.CASCADE,blank=True,null=True)
    name = models.CharField(max_length=100, unique=True)
    image = models.ImageField(null=True, blank=True)

    class Meta:
        verbose_name_plural = "Brands"

    def __str__(self):
        return self.name


class Collection(models.Model):
    name = models.CharField(max_length=100, unique=True)
    image = models.ImageField(null=True, blank=True)

    class Meta:
        verbose_name_plural = "Collections"

    def __str__(self):
        return self.name


class Variants(models.Model):
    SIZE = (
        ('not applicable', 'not applicable',),
        ('S', 'Small',),
        ('M', 'Medium',),
        ('L', 'Large',),
        ('XL', 'Extra Large',),
    )
    AVAILABILITY = (
        ('available', 'Available',),
        ('not_available', 'Not Available',),
    )
    product_id = models.CharField(max_length=70,default='OAXWRTZ_12C',blank=True)
    price = models.DecimalField(decimal_places=2, max_digits=20,default=500)
    size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True)
    color = models.CharField(max_length=70, default="not applicable",blank=True,null=True)
    variant_image = models.ImageField(upload_to="products/images", blank=True)
    thumbnail = ImageSpecField(source='variant_image',
                               processors=[ResizeToFill(100, 50)],
                               format='JPEG',
                               options={'quality': 60})
    quantity = models.IntegerField(default=10,blank=True,null=True)  # available quantity of given product
    variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available')

    class Meta:
        verbose_name_plural = "Variants"

    def __str__(self):
        return self.product_id

class Product(models.Model):   
    
    merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
    category = models.ManyToManyField(Category, blank=False)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
    featured = models.BooleanField(default=False)  # is product featured?
    best_seller = models.BooleanField(default=False)
    top_rated = models.BooleanField(default=False)

我的序列化器:

class BrandSerializer(serializers.ModelSerializer):
    # id = serializers.IntegerField()

    class Meta:
        model = Brand
        fields = '__all__'

class  AddProductSerializer(serializers.ModelSerializer):    
    merchant = serializers.PrimaryKeyRelatedField(read_only=True)
   
    class Meta:
        model = Product
        fields = ['id','merchant','category','brand', 'collection','featured', 'top_rated',
                  'name','description', 'picture','main_product_image','best_seller',
                  'rating','availability','warranty','services','variants']
        # depth = 1

    def create(self, validated_data):        
         product = Product.objects.create()
         return product

我的看法:

class ProductAddAPIView(CreateAPIView):
    permission_classes = [AllowAny]
    queryset = Product.objects.all()
    serializer_class = AddProductSerializer
           

标签: djangoapipostdjango-rest-frameworkpostman

解决方案


我认为问题出在序列化程序中的创建函数中

class  AddProductSerializer(serializers.ModelSerializer):    
    merchant = serializers.PrimaryKeyRelatedField(read_only=True)
   
    class Meta:
        model = Product
        fields = ['id','merchant','category','brand', 'collection','featured', 'top_rated',
                  'name','description', 'picture','main_product_image','best_seller',
                  'rating','availability','warranty','services','variants']
        # depth = 1

    def create(self, validated_data):        
         product = Product.objects.create()
         return product

由于您没有传递经过验证的数据,因此它创建了一个空对象,请改用它

def create(self, validated_data):
    return Product.objects.create(**validated_data)

推荐阅读