我是Django的新手,正在尝试建立几个模型,但是遇到了一个错误,我似乎找不到解决方法。
这是我得到的错误: psycopg2.errors.UndefinedColumn:列carts_cartitem.cart_id不存在 第1行:选择“ carts_cartitem”。“ id”,“ carts_cartitem”。“ cart_id”,“ c ...
这是我的视图文件:
from django.shortcuts import render, HttpResponseRedirect
from django.urls import reverse
from products.models import Product
from .models import Cart, CartItem
def view(request):
try:
the_id = request.session['cart_id']
except:
the_id = None
if the_id:
cart = Cart.objects.get(id=the_id)
context = {'cart': cart}
else:
empty_message = 'Your cart is empty!'
context = {'empty': True, 'empty_message': empty_message}
template = 'cart/view.html'
return render(request, template, context)
def update_cart(request, slug):
try:
the_id = request.session['cart_id']
except:
#create a cart
new_cart = Cart()
new_cart.save()
request.session['cart_id'] = new_cart.id
the_id = new_cart.id
cart = Cart.objects.get(id=the_id)
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product)
if created:
print('created')
new_total = 0.00
for item in cart.cartitem_set.all():
line_total = float(item.product.price) * item.quantity
new_total += line_total
request.session['items_total'] = cart.cartitem_set.count() #count products
cart.total = new_total
cart.save()
return HttpResponseRedirect(reverse('cart'))
这些是我的模特:
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99)
sale_price = models.DecimalField(decimal_places=2, max_digits=100, null=True, blank=True)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add= True, auto_now=False)
updated = models.DateTimeField(auto_now_add= False, auto_now=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
class Meta:
unique_together = ('title', 'slug')
def get_absolute_url(self):
return reverse('single_product', kwargs={'slug': self.slug})
class Cart(models.Model):
total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
timestamp = models.DateTimeField(auto_now_add= True, auto_now=False)
updated = models.DateTimeField(auto_now_add= False, auto_now=True)
active = models.BooleanField(default=True)
def __str__(self):
return "Cart id: %s" %(self.id)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete = models.CASCADE, blank=True, null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
line_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2)
timestamp = models.DateTimeField(auto_now_add= True, auto_now=False)
updated = models.DateTimeField(auto_now_add= False, auto_now=True)
def __str__(self):
return self.product.title
跟踪:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/cart/slug_one/
Django Version: 2.2.1
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products',
'carts']
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:
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
84. return self.cursor.execute(sql, params)
The above exception (column carts_cartitem.cart_id does not exist
LINE 1: SELECT "carts_cartitem"."id", "carts_cartitem"."cart_id", "c...
^
) was the direct cause of the following exception:
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/me/Desktop/farmacia.testing/carts/views.py" in update_cart
44. cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/models/query.py" in get_or_create
538. return self.get(**kwargs), False
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/models/query.py" in get
402. num = len(clone)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/models/query.py" in __len__
256. self._fetch_all()
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all
1242. self._result_cache = list(self._iterable_class(self))
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
55. results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
1100. cursor.execute(sql, params)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
99. return super().execute(sql, params)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
67. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute_with_wrappers
76. return executor(sql, params, many, context)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
84. return self.cursor.execute(sql, params)
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/me/.local/share/virtualenvs/farmacia.testing-0E8ur1aw/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
84. return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /cart/slug_one/
Exception Value: column carts_cartitem.cart_id does not exist
LINE 1: SELECT "carts_cartitem"."id", "carts_cartitem"."cart_id", "c...
答案 0 :(得分:0)
好像carts_cartitem表已损坏。正如一些人指出的那样,当我看表时不存在cart_id。由于某些原因,我无法更新迁移。解决方法是删除数据库并重新运行迁移,现在可以按预期运行。