【问题标题】:IntegrityError: null value in column "is_approved" violates not-null constraintIntegrityError:“is_approved”列中的空值违反非空约束
【发布时间】:2021-05-03 12:49:13
【问题描述】:

首先,我被告知要在我的模型中添加一个字段,以帮助管理员批准、不批准或挂起产品,然后才能在网站上看到它们。所以,我加了

class Product(models.Model):
  ...there are some fields here...
  is_approved = models.BooleanField(default=False)

到我的产品模型,进行例行迁移,编辑序列化程序、视图、url,对其进行测试并推送到 microsoft azure。

第二,我有另一条指令将同一字段更改为 approval_status

STATUS = [
    ('0', 'Pending Approval'),
    ('1', 'Approved'),
    ('2', 'Rejected')
] 

class Product(models.Model):
  ...there are some filed here...
     approval_status = models.CharField(
        choices=STATUS,
        default='0',
        max_length=2
    )

部署后出现这个错误

/marketplace/create_product/ 处的 IntegrityError “is_approved”列中的空值违反非空约束 详细信息:失败行包含 (620, , , 2.00, FTF, 0, PR, , , , 113, 2021-05-03 11:38:28.57937+00, null, 0)。*

我怀疑服务器数据库无法用 approval_status 替换 is_approved 字段,而是将其包含在内,因此试图返回该值。 我期待 13 个字段,但返回了 14 个 请帮助我解决错误的想法。

我的模特

class Product(models.Model):
    owner = models.ForeignKey(
        'Accounts.BusinessInfo',
        on_delete=models.CASCADE
    )
    name = models.CharField(
        max_length=100,
        blank=True,
    )
    description = models.TextField(
        blank=True
    )
    price = models.DecimalField(
        max_digits=10,
        decimal_places=2
    )
    category = models.CharField(
        choices=CATEGORY_CHOICES,
        default='FTF',
        max_length=10
    )
    discount = models.IntegerField(
        default=0
    )
    product_type = models.CharField(
        choices=PRODUCT_TYPE,
        default='PR',
        max_length=2
    )
    image_1 = models.ImageField(
        upload_to='products',
        blank=True,
        null=True
    )
    image_2 = models.ImageField(
        upload_to='products',
        blank=True,
        null=True
    )
    image_3 = models.ImageField(
        upload_to='products',
        blank=True,
        null=True
    )
    timestamp = models.DateTimeField(
        auto_now=True
    )
    approval_status = models.CharField(
        choices=STATUS,
        default='0',
        max_length=2
    )

    def __str__(self):
        return f"{self.name}"

    def save(self, *args, **kwargs):
        if not self.owner.user.is_organization:
            raise ValueError('You have to be an organization to create a product')
        super().save(*args, **kwargs)

我的序列化器

class ProductSerializer(serializers.ModelSerializer):
    owner = BusinessInfoSerializer(read_only=True)

    class Meta:
        model = Product
        fields = [
            'id', 'owner', 'name', 'description', 'price', 'category', 'discount', 'product_type',
            'image_1', 'image_2', 'image_3', 'timestamp',  'approval_status'
        ]

        extra_kwargs = {
            'id': {'required': False, 'read_only': True},
            'owner': {'required': False},
        }

我的观点

class CreateProduct(generics.CreateAPIView):
    queryset = Product.objects
    model = Product
    serializer_class = ProductSerializer
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JWTAuthentication,)

    def perform_create(self, serializer):
        product_owner = BusinessInfo.objects.get(user=self.request.user)
        serializer.save(owner=product_owner)

我的网址

    path(
        'create_product/',
        CreateProduct.as_view(),
        name='CreateProduct'
    ),

0001_initial.py

        migrations.CreateModel(
            name='Product',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(blank=True, max_length=100)),
                ('description', models.TextField(blank=True)),
                ('price', models.DecimalField(decimal_places=2, max_digits=10)),
                ('category', models.CharField(choices=[('FTF', 'Fashion, Textiles and Fabrics'), ('JGP', 'Jewellery, Gifts and Parcels'), ('SSF', 'Shoes, Sandals and Footwears'), ('AT', 'Automobile and Transport'), ('BOS', 'Books and Office Supplies'), ('LFD', 'Lights, Furniture and Decor'), ('BeL', 'Beauty and Lifestyle'), ('BaL', 'Bags and Luggage'), ('EGG', 'Electronics, Gadgets and Garden Equipment'), ('TBP', 'Toiletries / Baby Products'), ('PTC', 'Phones, Tablets and Computers'), ('GrP', 'Groceries and Provisions'), ('SE', 'services'), ('ITM', 'Industrial Tools and Machinery'), ('REP', 'Real Estates and Properties'), ('HeP', 'Health and Pharmaceuticals'), ('PlP', 'Plastics and Rubbers'), ('HE', 'Hardware Equipment'), ('MI', 'Musical Instruments'), ('BCM', 'Building and Construction Materials'), ('SFE', 'Safety Equipment'), ('FDS', 'Food, Drinks and Snacks'), ('UGK', 'Utensils, Glassware and Kitchenware'), ('PC', 'Paints and Chemicals')], default='FTF', max_length=10)),
                ('discount', models.IntegerField(default=0)),
                ('product_type', models.CharField(choices=[('PR', 'product'), ('SE', 'services')], default='PR', max_length=2)),
                ('image_1', models.ImageField(blank=True, null=True, upload_to='products')),
                ('image_2', models.ImageField(blank=True, null=True, upload_to='products')),
                ('image_3', models.ImageField(blank=True, null=True, upload_to='products')),
                ('timestamp', models.DateTimeField(auto_now=True)),
                ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Accounts.businessinfo')),
            ],
        ),

0002_product_approval_status.py

class Migration(migrations.Migration):

    dependencies = [
        ('Marketplace', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='product',
            name='approval_status',
            field=models.CharField(choices=[('0', 'Pending Approval'), ('1', 'Approved'), ('2', 'Rejected')],
                                   default='0', max_length=2),
        ),
    ]

【问题讨论】:

  • 此数据可能来自上次迁移,您可以删除以前的数据库(或仅针对此模型)并重新测试吗?而且我建议不要在测试之前部署,因为您可以更轻松地调试
  • 你能显示你的迁移文件的内容吗?

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


【解决方案1】:

所以我通过手动转到 azure 上的生产服务器以查找 is_approved 字段并将其删除,因为不再需要它来解决此错误。我很惊讶migrations query 可以为我做到这一点,但我知道有一种方法可以做到这一点,而我还没有遇到过。

【讨论】:

    猜你喜欢
    • 2013-05-12
    • 1970-01-01
    • 2016-10-21
    • 2016-01-18
    • 2020-08-20
    • 2019-04-08
    • 2017-10-15
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多