Не удалось получить ограничение FOREIGN KEY при попытке сохранения, но тот же код работает в оболочке - PullRequest
0 голосов
/ 16 июня 2020

Я получаю эту ошибку FOREIGN KEY constraint failed при попытке сохранить некоторые записи в базе данных, но аналогичный код отлично работает при ручном запуске в оболочке. Мой код ниже:

Models.py

from django.contrib.auth.models import User
from sde.models import Invtypes
from corp.models import EveCharacter

class Cart(models.Model):
    client = models.ForeignKey(User,on_delete=models.CASCADE)
    item = models.ForeignKey(Invtypes,on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1,blank=False,null=False)
    price = models.IntegerField(default=0,blank=True,null=True)
    checkout = models.BooleanField(default=False)
    createdate = models.DateTimeField(auto_now_add=True,blank=True)

    @property
    def get_total_price(self):
        return self.price * self.quantity

    def __str__(self):
        return '%s x %s' % (self.item,self.quantity)

class Order(models.Model):
    uid = models.UUIDField(primary_key=True, default=uuid.uuid4,help_text="UID")
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    receiver = models.ForeignKey(EveCharacter,on_delete=models.CASCADE)
    totalprice = models.IntegerField(default=0,blank=False,null=False)

    ORDER_STATUS = (
        ('o','on hold'),
        ('f','finished'),
        ('c','canceled'),
        ('e','exception'),
    )

    status = models.CharField(max_length=1, choices=ORDER_STATUS, blank=True, default='o')

    createdate = models.DateTimeField(auto_now_add=True,blank=True)
    finishdate = models.DateTimeField(blank=True,null=True)

    class Meta:
        ordering = ["createdate"]

    def get_absolute_url(self):
        return reverse('order-detail', args=[str(self.uid)])

    def __str__(self):
        return '%s (%s-%s)' % (self.receiver,self.status,self.uid)

class OrderUnit(models.Model):
    uid = models.UUIDField(primary_key=True, default=uuid.uuid4)
    order = models.ForeignKey('Order',on_delete=models.CASCADE)
    item = models.ForeignKey(Invtypes,on_delete=models.CASCADE)
    quantity = models.IntegerField(default=0,blank=False,null=False,help_text="product amount")
    price = models.IntegerField(default=0,blank=False,null=False)

    ITEM_STATUS = (
        ('w','Waiting for processing'),
        ('s','Sent'),
        ('p','Partially Sent'),
        ('e','Out of stock'),
    )
    status = models.CharField(max_length=1, choices=ITEM_STATUS, blank=True, default='w')

    def __str__(self):
        return '%s x %s (%s-%s)' % (self.item,self.quantity,self.status,self.uid)

Views.py

@login_required
def create_order(request):
    if request.method == 'POST':
        cartlist = request.POST.getlist('cart') #Get a list of submitted items
        character = EveCharacter.objects.get(name=request.POST.get('character')) #Get recipient
        order = Order(receiver=character,user=request.user) #Create Order
        totalprice = 0
        for cart in cartlist:
            r_cart = Cart.objects.get(pk=cart)
            temp = OrderUnit(order=order,item=r_cart.item,quantity=r_cart.quantity,price=r_cart.price) #These all have the correct values
            temp.save() #Get FOREIGN KEY constraint failed
            r_cart.checkout = True
            r_cart.save()
            totalprice += temp.price
        order.totalprice = totalprice
        order.save() #Order can be saved without error

    return render(request,'order/submit_order.html')

И трассировка

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/order/create/

Django Version: 3.0.5
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'sde.apps.SdeConfig',
 'corp.apps.CorpConfig',
 'cart.apps.CartConfig',
 'order.apps.OrderConfig',
 'mptt']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)

The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "D:\Work\django_test\evebackend2\order\views.py", line 25, in create_order
    temp.save()
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 745, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 782, in save_base
    updated = self._save_table(
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 924, in _do_insert
    return manager._insert(
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1391, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\neoha\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /order/create/
Exception Value: FOREIGN KEY constraint failed

1 Ответ

1 голос
/ 16 июня 2020

Проблема в том, что вы пытаетесь сохранить OrderUnit, у которого есть внешний ключ, в Order перед сохранением Order. Вы создали python объект Order, но не отправили его в базу данных. Вызовите order.save () перед temp.save (), перед вашим l oop

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...