简体   繁体   English

django 中的 IntegrityError 主键无效

[英]IntegrityError Primary Key Invalid in django

Something fixed in Order Class of model.在 model 的订单 Class 中修复了一些问题。 and then, I run migrate.然后,我运行迁移。 But, it is shown an error as但是,它显示为错误

django.db.utils.IntegrityError: The row in table 'core_order' with primary >key '4' has an invalid foreign key: core_order.billing_address_id contains a >value '1' that does not have a corresponding value in core_address.id. django.db.utils.IntegrityError:表“core_order”中主键为“4”的行具有无效的外键:core_order.billing_address_id 包含一个在core_address.id 中没有对应值的>值“1”。

Models.py模型.py

from django.conf import settings
from django.db import models
from django.db.models import Sum
from django.shortcuts import reverse
from django_countries.fields import CountryField

# Create your models here.
CATEGORY_CHOICES = (
    ('SB', 'Shirts And Blouses'),
    ('TS', 'T-Shirts'),
    ('SK', 'Skirts'),
    ('HS', 'Hoodies&Sweatshirts')
)

LABEL_CHOICES = (
    ('S', 'sale'),
    ('N', 'new'),
    ('P', 'promotion')
)


class Item(models.Model):
    title = models.CharField(max_length=100)
    price = models.FloatField()
    discount_price = models.FloatField(blank=True, null=True)
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
    label = models.CharField(choices=LABEL_CHOICES, max_length=1)
    slug = models.SlugField()
    description = models.TextField()
    image = models.ImageField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("core:product", kwargs={
            'slug': self.slug
        })

    def get_add_to_cart_url(self):
        return reverse("core:add-to-cart", kwargs={
            'slug': self.slug
        })

    def get_remove_from_cart_url(self):
        return reverse("core:remove-from-cart", kwargs={
            'slug': self.slug
        })


class OrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return f"{self.quantity} of {self.item.title}"

    def get_total_item_price(self):
        return self.quantity * self.item.price

    def get_total_discount_item_price(self):
        return self.quantity * self.item.discount_price

    def get_amount_saved(self):
        return self.get_total_item_price() - self.get_total_discount_item_price()

    def get_final_price(self):
        if self.item.discount_price:
            return self.get_total_discount_item_price()
        return self.get_total_item_price()


class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    ref_code = models.CharField(max_length=20)
    items = models.ManyToManyField(OrderItem)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField()
    ordered = models.BooleanField(default=False)
    billing_address = models.ForeignKey(
        'BillingAddress', on_delete=models.SET_NULL, blank=True, null=True)
    payment = models.ForeignKey(
        'Payment', on_delete=models.SET_NULL, blank=True, null=True)
    coupon = models.ForeignKey(
        'Coupon', on_delete=models.SET_NULL, blank=True, null=True)
    being_delivered = models.BooleanField(default=False)
    received = models.BooleanField(default=False)
    refund_requested = models.BooleanField(default=False)
    refund_granted = models.BooleanField(default=False)

    '''
    1. Item added to cart
    2. Adding a BillingAddress
    (Failed Checkout)
    3. Payment
    4. Being delivered
    5. Received
    6. Refunds
    '''

    def __str__(self):
        return self.user.username

    def get_total(self):
        total = 0
        for order_item in self.items.all():
            total += order_item.get_final_price()
        if self.coupon:
            total -= self.coupon.amount
        return total


class BillingAddress(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    street_address = models.CharField(max_length=100)
    apartment_address = models.CharField(max_length=100)
    country = CountryField(multiple=False)
    zip = models.CharField(max_length=100)

    def __str__(self):
        return self.user.username


class Payment(models.Model):
    stripe_charge_id = models.CharField(max_length=50)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.SET_NULL, blank=True, null=True)
    amount = models.FloatField()
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.user.username


class Coupon(models.Model):
    code = models.CharField(max_length=15)
    amount = models.FloatField()

    def __str__(self):
        return self.code


class Refund(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    reason = models.TextField()
    accepted = models.BooleanField(default=False)
    email = models.EmailField()

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

i undo to Previous code, but primary key error is still showing when i migrate我撤消到以前的代码,但是当我迁移时仍然显示主键错误

Deleted all the migration records except __init__.py file.删除了除__init__.py文件之外的所有迁移记录。

Also Deleted the db.sqlite3 file.还删除了db.sqlite3文件。

And Then, run following commands然后,运行以下命令

python manage.py makemigrations core
python manage.py migrate

Hope this Help希望这个帮助

For example, given an orders table and a customers table, if you create a column orders.customer_id that references the customers.id primary key:例如,给定一个 orders 表和一个 customers 表,如果您创建一个列orders.customer_id引用customers.id主键:

Each value that is inserted or updated in orders.customer_id must exactly match a value in customers.id , or be NULL.orders.customer_id中插入或更新的每个值都必须与customers.id中的值完全匹配,或者是 NULL。

Values in customers.id that are referenced by orders.customer_id cannot be deleted or updated, unless you have cascading actions.除非您有级联操作,否则无法删除或更新orders.customer_id引用的customers.id中的值。 However, values of customers.id that are not present in orders.customer_id can be deleted or updated.但是,可以删除或更新orders.customer_id中不存在的customers.id值。

If you made a mistake in a migration, the easiest way to undo it is to do the migration backwards.如果您在迁移中犯了错误,最简单的撤消方法是向后迁移。 For example, if you just created the 0003 migration:例如,如果您刚刚创建了 0003 迁移:

manage.py migrate your_app 0002
rm your_app/migrations/0003_*.py

You can also change the state of migrations without actually running them if you have an error:如果出现错误,您还可以更改迁移的 state 而无需实际运行它们:

manage.py migrate --fake your_app 0002

fix your database manually手动修复数据库

rm your_app/migrations/0003_*.py

Another way we can solve this problem on sqlite is:我们可以在 sqlite 上解决此问题的另一种方法是:

To remove the addresses table, you have to:要删除地址表,您必须:

Open sqlite.exe program a dbshell terminal will be opened, you see all the tables and schema there by following command:打开 sqlite.exe 程序将打开一个 dbshell 终端,您可以通过以下命令看到那里的所有表和架构:

.databases ( shows all the databases)

.schema * 

the ".schema" command shows the schema for all attached databases. “.schema”命令显示所有附加数据库的模式。 If you only want to see the schema for a single database (perhaps "main") then you can add an argument to ".schema" to restrict its output:如果您只想查看单个数据库(可能是“主”)的架构,那么您可以向“.schema”添加一个参数以限制其 output:

.schema main.* 

Now you can see the database and database index giving trouble.现在您可以看到数据库和数据库索引出现问题。 Now you need to: Disable foreign key constraints.现在您需要: 禁用外键约束。 Drop the addresses table.删除地址表。 Update the address_id in the people table to NULL values.将 people 表中的 address_id 更新为 NULL 值。 Enable the foreign key constraints.启用外键约束。

PRAGMA foreign_keys = OFF;

DROP TABLE addresses;

UPDATE people
SET address_id = NULL;

PRAGMA foreign_keys = ON;

On the above example, you can assume there are two tables People and Addresses.在上面的示例中,您可以假设有两个表 People 和 Addresses。 People table uses Address ID as foreign_key from address.人员表使用地址 ID 作为地址中的外键。 Due to foreign_key constraints, we were unable to delete the table or we were unable to modify the table.由于foreign_key 约束,我们无法删除该表或无法修改该表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM