首页 > 编程问答 >通过选择不同的大小来更改价格电子商务应用程序时,我在不支持的操作数类型中收到错误

通过选择不同的大小来更改价格电子商务应用程序时,我在不支持的操作数类型中收到错误

时间:2024-07-20 17:48:05浏览次数:11  
标签:python django

unsupported operand type(s) for +: 'int' and 'str'
Internal Server Error: /product/t-shirts/
Traceback (most recent call last):
  File "C:\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
    self.check_response(response, callback)
  File "C:\Python311\Lib\site-packages\django\core\handlers\base.py", line 332, in check_response
    raise ValueError(
ValueError: The view products.views.get_product didn't return an HttpResponse object. It returned None instead.
[20/Jul/2024 12:48:11] "GET /product/t-shirts/?size=XL HTTP/1.1" 500 68697

这是我的 products.models 页面

from django.db import models

from base.models import BaseModel

from django.utils.text import slugify


class Category(BaseModel):
    category_name = models.CharField(max_length=100)

    slug = models.SlugField(unique=True, null=True, blank=True)

    category_image = models.ImageField(upload_to="categories")

    def save(self, *args, **kwargs):
        self.slug = slugify(self.category_name)

        super(Category, self).save(*args, **kwargs)

    def __str__(self) -> str:
        return self.category_name


class ColorVariant(BaseModel):
    color_name = models.CharField(max_length=100)

    price = models.CharField(max_length=100)

    def __str__(self) -> str:
        return self.color_name


class SizeVariant(BaseModel):
    size_name = models.CharField(max_length=100)

    price = models.CharField(max_length=100)

    def __str__(self) -> str:
        return self.size_name


class Product(BaseModel):
    product_name = models.CharField(max_length=100)

    slug = models.SlugField(unique=True, null=True, blank=True)

    categorys = models.ForeignKey(
        Category,
        on_delete=models.CASCADE,
        related_name="products",
        blank=False,
        null=True,
    )
    price = models.IntegerField()

    products_description = models.TextField()

    color_variant = models.ManyToManyField(ColorVariant, blank=True)

    size_variant = models.ManyToManyField(SizeVariant, blank=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.product_name)
        super(Product, self).save(*args, **kwargs)

    def __str__(self) -> str:
        return self.product_nam

    def get_product_price_by_size(self, size):
        return self.price + str(SizeVariant.objects.get(size_name=size).price)


class ProductImage(BaseModel):
    products = models.ForeignKey(
        Product, on_delete=models.CASCADE, related_name="product_images"
    )

    image = models.ImageField(upload_to="product")

The error message "unsupported operand type(s) for +: 'int' and 'str'" means that you are trying to add an integer and a string together, which is not allowed in Python.

Looking at your code, the problem lies in the get_product_price_by_size method of your Product model:

def get_product_price_by_size(self, size):
    return self.price + str(SizeVariant.objects.get(size_name=size).price) 

Here's what's happening:

  1. self.price is an integer. You defined it as price = models.IntegerField() in the Product model.
  2. SizeVariant.objects.get(size_name=size).price retrieves a string. You defined price as a CharField in the SizeVariant model.
  3. You're trying to add the integer ( self.price ) and the string ( SizeVariant.objects.get(size_name=size).price ) together. This results in the "unsupported operand type(s)" error because Python doesn't know if you want to concatenate the values as strings or add them as numbers.

To fix this, you should ensure both values are treated as numbers:

  1. Change price in SizeVariant to an IntegerField : ```python class SizeVariant(BaseModel): size_name = models.CharField(max_length=100) price = models.IntegerField() # Change to IntegerField

    def str (self) -> str: return self.size_name ```

  2. Modify the get_product_price_by_size method: python def get_product_price_by_size(self, size): size_variant = SizeVariant.objects.get(size_name=size) return self.price + size_variant.price

This modification ensures that both self.price and size_variant.price are integers before they are added together.

After making these changes, remember to run migrations:

python manage.py makemigrations
python manage.py migrate

This will update your database schema to reflect the changes you made to your model.

标签:python,django
From: 78772157

相关文章

  • 在pyspark(python)中将json字符串扩展到多列
    我需要将Json对象(b列)扩展到多列。从此表中,A列B列id1[{a:1,b:'letter1'}]id2[{a:1,b:'letter2',c:3,d:4}]对......
  • python实现文件的读写
    python实现文件的读写路径的书写:open("E:\\ai_03\\code\\ai_03_python\\day07\\data.txt")#两个斜杠open(r"E:\ai_03\code\ai_03_python\day07\data.txt","w",encoding="utf8")#建议使用读文件读文件的格式要以读文件的模式打开一个文件对象,使用Python......
  • python模块化设计
    在Python中,模块化是将代码分解为独立的功能块,并通过导入和使用这些功能块来实现代码复用和组织的一种方式。模块化的编程风格使得代码更易于维护、扩展和测试。以下是Python实现模块化的一些常用方法:使用import语句导入模块:可以使用import语句导入其他Python文件(.py文件)作为......
  • 5分钟解锁python多线程
    以下是一个使用Python多线程的简单示例代码:importthreadingdefprint_numbers():foriinrange(1,6):print(i)defprint_letters():forletterin['A','B','C','D','E']:print(letter)if__nam......
  • 看过来!看过来!python九大数据类型大整合!
    目录一、Int(整型)二、Float(浮点型)三、Bool(布尔类型)四、Str(字符串)(1)拼接:(2)格式化:(3)查找和替换:(4)分割和连接:(5)大小写转换:(6)去除空白字符:五、None(空值)初始化变量作为函数的返回值:在条件语句中检查:六、List(列表)创建List访问List元素修改ListList的遍历七......
  • win系统 python 安装 osgeo库安装(最简单)
    Python osgeo库安装用法介绍安装使用osgeo库,本质是安装gdal一、下载对应python版本压缩包下载地址在结尾二、解压压缩包在解压之后的文件夹当中,找到这两个文件夹三、复制文件夹到python安装目录当中如python环境文件夹路径为D:\Local\Programs\miniconda3\envs\py31......
  • 【Python】使用库 -- 详解
    库就是别人已经写好了的代码,可以让我们直接拿来用。一个编程语言能不能流行起来,一方面取决于语法是否简单方便容易学习,一方面取决于生态是否完备。所谓的“生态” 指的就是语言是否有足够丰富的库,来应对各种各样的场景。在实际开发中,也并非所有的代码都自己手写,而是要充分利......
  • python函数基础
    1.函数目的函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率。函数可以封装一定的功能2.函数的定义函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()。任何传入参数和自变量必须放在圆括号中间,圆括......
  • Python游戏开发实践项目-小恐龙躲避游戏——一个适合python新手练手的项目
    今天我们就来给大家演示下,用Python来自己做一个仿制的“小恐龙游戏”!废话不多说,让我们愉快地开始吧~相关模块:pygame模块;以及一些python自带的模块。环境搭建安装Python并添加到环境变量,pip安装需要的相关模块即可。先睹为快在终端运行如下命令即可:pythonGame7.py......
  • python 类
    构造方法init方法说明参数self->指的就是实例对象自己,返回值为空,实际是调用了new方法会生成一个实例对象实例化类的时候系统自动调用init方法进行创建(在调用init方法直接系统自动调用new方法创建对象)对象和初始化如果类没有init方法,系统会调用默认的;如果写了就相当于对init......